1<?php
2namespace GuzzleHttp\Cookie;
3
4/**
5 * Persists non-session cookies using a JSON formatted file
6 */
7class FileCookieJar extends CookieJar
8{
9    /** @var string filename */
10    private $filename;
11
12    /** @var bool Control whether to persist session cookies or not. */
13    private $storeSessionCookies;
14
15    /**
16     * Create a new FileCookieJar object
17     *
18     * @param string $cookieFile        File to store the cookie data
19     * @param bool $storeSessionCookies Set to true to store session cookies
20     *                                  in the cookie jar.
21     *
22     * @throws \RuntimeException if the file cannot be found or created
23     */
24    public function __construct($cookieFile, $storeSessionCookies = false)
25    {
26        parent::__construct();
27        $this->filename = $cookieFile;
28        $this->storeSessionCookies = $storeSessionCookies;
29
30        if (file_exists($cookieFile)) {
31            $this->load($cookieFile);
32        }
33    }
34
35    /**
36     * Saves the file when shutting down
37     */
38    public function __destruct()
39    {
40        $this->save($this->filename);
41    }
42
43    /**
44     * Saves the cookies to a file.
45     *
46     * @param string $filename File to save
47     * @throws \RuntimeException if the file cannot be found or created
48     */
49    public function save($filename)
50    {
51        $json = [];
52        foreach ($this as $cookie) {
53            /** @var SetCookie $cookie */
54            if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
55                $json[] = $cookie->toArray();
56            }
57        }
58
59        $jsonStr = \GuzzleHttp\json_encode($json);
60        if (false === file_put_contents($filename, $jsonStr, LOCK_EX)) {
61            throw new \RuntimeException("Unable to save file {$filename}");
62        }
63    }
64
65    /**
66     * Load cookies from a JSON formatted file.
67     *
68     * Old cookies are kept unless overwritten by newly loaded ones.
69     *
70     * @param string $filename Cookie file to load.
71     * @throws \RuntimeException if the file cannot be loaded.
72     */
73    public function load($filename)
74    {
75        $json = file_get_contents($filename);
76        if (false === $json) {
77            throw new \RuntimeException("Unable to load file {$filename}");
78        } elseif ($json === '') {
79            return;
80        }
81
82        $data = \GuzzleHttp\json_decode($json, true);
83        if (is_array($data)) {
84            foreach (json_decode($json, true) as $cookie) {
85                $this->setCookie(new SetCookie($cookie));
86            }
87        } elseif (strlen($data)) {
88            throw new \RuntimeException("Invalid cookie file: {$filename}");
89        }
90    }
91}
92