SessionCookieJar.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace GuzzleHttp\Cookie;
  3. /**
  4. * Persists cookies in the client session
  5. */
  6. class SessionCookieJar extends CookieJar
  7. {
  8. /** @var string session key */
  9. private $sessionKey;
  10. /** @var bool Control whether to persist session cookies or not. */
  11. private $storeSessionCookies;
  12. /**
  13. * Create a new SessionCookieJar object
  14. *
  15. * @param string $sessionKey Session key name to store the cookie
  16. * data in session
  17. * @param bool $storeSessionCookies Set to true to store session cookies
  18. * in the cookie jar.
  19. */
  20. public function __construct($sessionKey, $storeSessionCookies = false)
  21. {
  22. parent::__construct();
  23. $this->sessionKey = $sessionKey;
  24. $this->storeSessionCookies = $storeSessionCookies;
  25. $this->load();
  26. }
  27. /**
  28. * Saves cookies to session when shutting down
  29. */
  30. public function __destruct()
  31. {
  32. $this->save();
  33. }
  34. /**
  35. * Save cookies to the client session
  36. */
  37. public function save()
  38. {
  39. $json = [];
  40. foreach ($this as $cookie) {
  41. /** @var SetCookie $cookie */
  42. if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
  43. $json[] = $cookie->toArray();
  44. }
  45. }
  46. $_SESSION[$this->sessionKey] = json_encode($json);
  47. }
  48. /**
  49. * Load the contents of the client session into the data array
  50. */
  51. protected function load()
  52. {
  53. if (!isset($_SESSION[$this->sessionKey])) {
  54. return;
  55. }
  56. $data = json_decode($_SESSION[$this->sessionKey], true);
  57. if (is_array($data)) {
  58. foreach ($data as $cookie) {
  59. $this->setCookie(new SetCookie($cookie));
  60. }
  61. } elseif (strlen($data)) {
  62. throw new \RuntimeException("Invalid cookie data");
  63. }
  64. }
  65. }