Nav apraksta

SessionCookieJar.php 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 presist 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. $this->sessionKey = $sessionKey;
  23. $this->storeSessionCookies = $storeSessionCookies;
  24. $this->load();
  25. }
  26. /**
  27. * Saves cookies to session when shutting down
  28. */
  29. public function __destruct()
  30. {
  31. $this->save();
  32. }
  33. /**
  34. * Save cookies to the client session
  35. */
  36. public function save()
  37. {
  38. $json = [];
  39. foreach ($this as $cookie) {
  40. /** @var SetCookie $cookie */
  41. if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
  42. $json[] = $cookie->toArray();
  43. }
  44. }
  45. $_SESSION[$this->sessionKey] = json_encode($json);
  46. }
  47. /**
  48. * Load the contents of the client session into the data array
  49. */
  50. protected function load()
  51. {
  52. $cookieJar = isset($_SESSION[$this->sessionKey])
  53. ? $_SESSION[$this->sessionKey]
  54. : null;
  55. $data = json_decode($cookieJar, true);
  56. if (is_array($data)) {
  57. foreach ($data as $cookie) {
  58. $this->setCookie(new SetCookie($cookie));
  59. }
  60. } elseif (strlen($data)) {
  61. throw new \RuntimeException("Invalid cookie data");
  62. }
  63. }
  64. }