SessionCookieJar.php 2.0 KB

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