]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/CoreBundle/Helper/FileCookieJar.php
Cleanup cookie jar
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Helper / FileCookieJar.php
CommitLineData
9a80dcf1
JB
1<?php
2
3namespace Wallabag\CoreBundle\Helper;
4
5use GuzzleHttp\Cookie\FileCookieJar as BaseFileCookieJar;
6use GuzzleHttp\Cookie\SetCookie;
7use GuzzleHttp\Utils;
51d7f62b 8use Psr\Log\LoggerInterface;
9a80dcf1
JB
9
10/**
11 * Overidden Cookie behavior to:
9a80dcf1
JB
12 * - ignore error when the cookie file is malformatted (resulting in clearing it).
13 */
14class FileCookieJar extends BaseFileCookieJar
15{
51d7f62b
JB
16 private $logger;
17
18 /**
19 * @param LoggerInterface $logger Only used to log info when something goes wrong
20 * @param string $cookieFile File to store the cookie data
21 */
22 public function __construct(LoggerInterface $logger, $cookieFile)
23 {
24 parent::__construct($cookieFile);
25
26 $this->logger = $logger;
27 }
28
9a80dcf1
JB
29 /**
30 * Load cookies from a JSON formatted file.
31 *
32 * Old cookies are kept unless overwritten by newly loaded ones.
33 *
34 * @param string $filename cookie file to load
35 *
36 * @throws \RuntimeException if the file cannot be loaded
37 */
38 public function load($filename)
39 {
40 $json = file_get_contents($filename);
41 if (false === $json) {
42 // @codeCoverageIgnoreStart
43 throw new \RuntimeException("Unable to load file {$filename}");
44 // @codeCoverageIgnoreEnd
45 }
46
47 try {
48 $data = Utils::jsonDecode($json, true);
49 } catch (\InvalidArgumentException $e) {
51d7f62b
JB
50 $this->logger->error('JSON inside the cookie is broken', [
51 'json' => $json,
52 'error_msg' => $e->getMessage(),
53 ]);
54
9a80dcf1
JB
55 // cookie file is invalid, just ignore the exception and it'll reset the whole cookie file
56 $data = '';
57 }
58
59 if (\is_array($data)) {
60 foreach (Utils::jsonDecode($json, true) as $cookie) {
61 $this->setCookie(new SetCookie($cookie));
62 }
63 } elseif (\strlen($data)) {
64 throw new \RuntimeException("Invalid cookie file: {$filename}");
65 }
66 }
67}