3 namespace Wallabag\CoreBundle\Helper
;
5 use GuzzleHttp\Cookie\FileCookieJar
as BaseFileCookieJar
;
6 use GuzzleHttp\Cookie\SetCookie
;
8 use Psr\Log\LoggerInterface
;
11 * Overidden Cookie behavior to:
12 * - fix multiple concurrent writes (see https://github.com/guzzle/guzzle/pull/1884)
13 * - ignore error when the cookie file is malformatted (resulting in clearing it).
15 class FileCookieJar
extends BaseFileCookieJar
20 * @param LoggerInterface $logger Only used to log info when something goes wrong
21 * @param string $cookieFile File to store the cookie data
23 public function __construct(LoggerInterface
$logger, $cookieFile)
25 parent
::__construct($cookieFile);
27 $this->logger
= $logger;
31 * Saves the cookies to a file.
33 * @param string $filename File to save
35 * @throws \RuntimeException if the file cannot be found or created
37 public function save($filename)
40 foreach ($this as $cookie) {
41 if ($cookie->getExpires() && !$cookie->getDiscard()) {
42 $json[] = $cookie->toArray();
46 if (false === file_put_contents($filename, json_encode($json), LOCK_EX
)) {
47 // @codeCoverageIgnoreStart
48 throw new \
RuntimeException("Unable to save file {$filename}");
49 // @codeCoverageIgnoreEnd
54 * Load cookies from a JSON formatted file.
56 * Old cookies are kept unless overwritten by newly loaded ones.
58 * @param string $filename cookie file to load
60 * @throws \RuntimeException if the file cannot be loaded
62 public function load($filename)
64 $json = file_get_contents($filename);
65 if (false === $json) {
66 // @codeCoverageIgnoreStart
67 throw new \
RuntimeException("Unable to load file {$filename}");
68 // @codeCoverageIgnoreEnd
72 $data = Utils
::jsonDecode($json, true);
73 } catch (\InvalidArgumentException
$e) {
74 $this->logger
->error('JSON inside the cookie is broken', [
76 'error_msg' => $e->getMessage(),
79 // cookie file is invalid, just ignore the exception and it'll reset the whole cookie file
83 if (\
is_array($data)) {
84 foreach (Utils
::jsonDecode($json, true) as $cookie) {
85 $this->setCookie(new SetCookie($cookie));
87 } elseif (\
strlen($data)) {
88 throw new \
RuntimeException("Invalid cookie file: {$filename}");