SessionCookieJar.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\HttpMessage\Cookie;
  12. use RuntimeException;
  13. /**
  14. * Persists cookies in the client session for FPM.
  15. */
  16. class SessionCookieJar extends CookieJar
  17. {
  18. /**
  19. * Create a new SessionCookieJar object.
  20. *
  21. * @param string $sessionKey Session key name to store the cookie
  22. * data in session
  23. * @param bool $storeSessionCookies Control whether to persist session cookies or not.
  24. * set to true to store session cookies
  25. * in the cookie jar
  26. */
  27. public function __construct(private string $sessionKey, private bool $storeSessionCookies = false)
  28. {
  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. foreach ($this as $cookie) {
  45. /** @var SetCookie $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. }