]>
Commit | Line | Data |
---|---|---|
9a80dcf1 JB |
1 | <?php |
2 | ||
3 | namespace Wallabag\CoreBundle\Helper; | |
4 | ||
5 | use GuzzleHttp\Cookie\FileCookieJar as BaseFileCookieJar; | |
6 | use GuzzleHttp\Cookie\SetCookie; | |
7 | use GuzzleHttp\Utils; | |
8 | ||
9 | /** | |
10 | * Overidden Cookie behavior to: | |
11 | * - fix multiple concurrent writes (see https://github.com/guzzle/guzzle/pull/1884) | |
12 | * - ignore error when the cookie file is malformatted (resulting in clearing it). | |
13 | */ | |
14 | class FileCookieJar extends BaseFileCookieJar | |
15 | { | |
16 | /** | |
17 | * Saves the cookies to a file. | |
18 | * | |
19 | * @param string $filename File to save | |
20 | * | |
21 | * @throws \RuntimeException if the file cannot be found or created | |
22 | */ | |
23 | public function save($filename) | |
24 | { | |
25 | $json = []; | |
26 | foreach ($this as $cookie) { | |
27 | if ($cookie->getExpires() && !$cookie->getDiscard()) { | |
28 | $json[] = $cookie->toArray(); | |
29 | } | |
30 | } | |
31 | ||
32 | if (false === file_put_contents($filename, json_encode($json), LOCK_EX)) { | |
33 | // @codeCoverageIgnoreStart | |
34 | throw new \RuntimeException("Unable to save file {$filename}"); | |
35 | // @codeCoverageIgnoreEnd | |
36 | } | |
37 | } | |
38 | ||
39 | /** | |
40 | * Load cookies from a JSON formatted file. | |
41 | * | |
42 | * Old cookies are kept unless overwritten by newly loaded ones. | |
43 | * | |
44 | * @param string $filename cookie file to load | |
45 | * | |
46 | * @throws \RuntimeException if the file cannot be loaded | |
47 | */ | |
48 | public function load($filename) | |
49 | { | |
50 | $json = file_get_contents($filename); | |
51 | if (false === $json) { | |
52 | // @codeCoverageIgnoreStart | |
53 | throw new \RuntimeException("Unable to load file {$filename}"); | |
54 | // @codeCoverageIgnoreEnd | |
55 | } | |
56 | ||
57 | try { | |
58 | $data = Utils::jsonDecode($json, true); | |
59 | } catch (\InvalidArgumentException $e) { | |
60 | // cookie file is invalid, just ignore the exception and it'll reset the whole cookie file | |
61 | $data = ''; | |
62 | } | |
63 | ||
64 | if (\is_array($data)) { | |
65 | foreach (Utils::jsonDecode($json, true) as $cookie) { | |
66 | $this->setCookie(new SetCookie($cookie)); | |
67 | } | |
68 | } elseif (\strlen($data)) { | |
69 | throw new \RuntimeException("Invalid cookie file: {$filename}"); | |
70 | } | |
71 | } | |
72 | } |