scratch – Blame information for rev 87
?pathlinks?
Rev | Author | Line No. | Line |
---|---|---|---|
87 | office | 1 | <?php |
2 | |||
3 | namespace GuzzleHttp\Cookie; |
||
4 | |||
5 | /** |
||
6 | * Persists cookies in the client session |
||
7 | */ |
||
8 | class SessionCookieJar extends CookieJar |
||
9 | { |
||
10 | /** @var string session key */ |
||
11 | private $sessionKey; |
||
12 | |||
13 | /** |
||
14 | * Create a new SessionCookieJar object |
||
15 | * |
||
16 | * @param string $sessionKey Session key name to store the cookie data in session |
||
17 | */ |
||
18 | public function __construct($sessionKey) |
||
19 | { |
||
20 | $this->sessionKey = $sessionKey; |
||
21 | $this->load(); |
||
22 | } |
||
23 | |||
24 | /** |
||
25 | * Saves cookies to session when shutting down |
||
26 | */ |
||
27 | public function __destruct() |
||
28 | { |
||
29 | $this->save(); |
||
30 | } |
||
31 | |||
32 | /** |
||
33 | * Save cookies to the client session |
||
34 | */ |
||
35 | public function save() |
||
36 | { |
||
37 | $json = []; |
||
38 | foreach ($this as $cookie) { |
||
39 | if ($cookie->getExpires() && !$cookie->getDiscard()) { |
||
40 | $json[] = $cookie->toArray(); |
||
41 | } |
||
42 | } |
||
43 | |||
44 | $_SESSION[$this->sessionKey] = json_encode($json); |
||
45 | } |
||
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 | |||
56 | $data = \GuzzleHttp\json_decode($cookieJar, 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 | } |