Subversion Repositories cheapmusic

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
103 - 1
<?php
2
namespace GuzzleHttp\Cookie;
3
 
4
/**
5
 * Persists cookies in the client session
6
 */
7
class 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
        $this->sessionKey = $sessionKey;
26
        $this->storeSessionCookies = $storeSessionCookies;
27
        $this->load();
28
    }
29
 
30
    /**
31
     * Saves cookies to session when shutting down
32
     */
33
    public function __destruct()
34
    {
35
        $this->save();
36
    }
37
 
38
    /**
39
     * Save cookies to the client session
40
     */
41
    public function save()
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
 
51
        $_SESSION[$this->sessionKey] = json_encode($json);
52
    }
53
 
54
    /**
55
     * Load the contents of the client session into the data array
56
     */
57
    protected function load()
58
    {
59
        if (!isset($_SESSION[$this->sessionKey])) {
60
            return;
61
        }
62
        $data = json_decode($_SESSION[$this->sessionKey], true);
63
        if (is_array($data)) {
64
            foreach ($data as $cookie) {
65
                $this->setCookie(new SetCookie($cookie));
66
            }
67
        } elseif (strlen($data)) {
68
            throw new \RuntimeException("Invalid cookie data");
69
        }
70
    }
71
}