Open Monograph Press  3.3.0
vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php
1 <?php
2 namespace GuzzleHttp\Cookie;
3 
7 class FileCookieJar extends CookieJar
8 {
10  private $filename;
11 
13  private $storeSessionCookies;
14 
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 
38  public function __destruct()
39  {
40  $this->save($this->filename);
41  }
42 
49  public function save($filename)
50  {
51  $json = [];
52  foreach ($this as $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 
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 }
GuzzleHttp\Cookie
Definition: guzzlehttp/guzzle/src/Cookie/CookieJar.php:2
GuzzleHttp\Cookie\SetCookie
Definition: SetCookie.php:7
GuzzleHttp\Cookie\FileCookieJar
Definition: vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php:7
GuzzleHttp\Cookie\CookieJar\shouldPersist
static shouldPersist(SetCookie $cookie, $allowSessionCookies=false)
Definition: guzzlehttp/guzzle/src/Cookie/CookieJar.php:82
GuzzleHttp\Cookie\CookieJar\setCookie
setCookie(SetCookie $cookie)
Definition: guzzlehttp/guzzle/src/Cookie/CookieJar.php:165
GuzzleHttp\Cookie\FileCookieJar\load
load($filename)
Definition: vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php:79
GuzzleHttp\json_decode
json_decode($json, $assoc=false, $depth=512, $options=0)
Definition: guzzlehttp/guzzle/src/functions.php:301
GuzzleHttp\Cookie\FileCookieJar\save
save($filename)
Definition: vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php:55
GuzzleHttp\Cookie\FileCookieJar\__construct
__construct($cookieFile, $storeSessionCookies=false)
Definition: vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php:30
GuzzleHttp\Cookie\FileCookieJar\__destruct
__destruct()
Definition: vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php:44
GuzzleHttp\Cookie\CookieJar
Definition: guzzlehttp/guzzle/src/Cookie/CookieJar.php:10