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