| 1 |
<?php |
| 2 |
|
| 3 |
namespace GuzzleHttp\Cookie; |
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
class SessionCookieJar extends CookieJar |
| 9 |
{ |
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
private $sessionKey; |
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
private $storeSessionCookies; |
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
public function __construct(string $sessionKey, bool $storeSessionCookies = false) |
| 29 |
{ |
| 30 |
parent::__construct(); |
| 31 |
$this->sessionKey = $sessionKey; |
| 32 |
$this->storeSessionCookies = $storeSessionCookies; |
| 33 |
$this->load(); |
| 34 |
} |
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
public function __destruct() |
| 40 |
{ |
| 41 |
$this->save(); |
| 42 |
} |
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
public function save(): void |
| 48 |
{ |
| 49 |
$json = []; |
| 50 |
|
| 51 |
foreach ($this as $cookie) { |
| 52 |
if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) { |
| 53 |
$json[] = $cookie->toArray(); |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
$json = \json_encode($json); |
| 58 |
if (false === $json) { |
| 59 |
throw new \RuntimeException('Unable to encode cookie data'); |
| 60 |
} |
| 61 |
|
| 62 |
$_SESSION[$this->sessionKey] = $json; |
| 63 |
} |
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
protected function load(): void |
| 69 |
{ |
| 70 |
if (!isset($_SESSION[$this->sessionKey])) { |
| 71 |
return; |
| 72 |
} |
| 73 |
|
| 74 |
$json = $_SESSION[$this->sessionKey]; |
| 75 |
if (!\is_string($json)) { |
| 76 |
throw new \RuntimeException('Invalid cookie data'); |
| 77 |
} |
| 78 |
|
| 79 |
$data = \json_decode($json, true); |
| 80 |
if (\is_array($data)) { |
| 81 |
foreach ($data as $cookie) { |
| 82 |
if (!\is_array($cookie)) { |
| 83 |
throw new \RuntimeException('Invalid cookie data'); |
| 84 |
} |
| 85 |
|
| 86 |
$this->setCookie(new SetCookie($cookie)); |
| 87 |
} |
| 88 |
} elseif (\is_scalar($data) && \strlen((string) $data)) { |
| 89 |
throw new \RuntimeException('Invalid cookie data'); |
| 90 |
} |
| 91 |
} |
| 92 |
} |