Chris@0: filename = $cookieFile; Chris@0: $this->storeSessionCookies = $storeSessionCookies; Chris@0: Chris@0: if (file_exists($cookieFile)) { Chris@0: $this->load($cookieFile); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Saves the file when shutting down Chris@0: */ Chris@0: public function __destruct() Chris@0: { Chris@0: $this->save($this->filename); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Saves the cookies to a file. Chris@0: * Chris@0: * @param string $filename File to save Chris@0: * @throws \RuntimeException if the file cannot be found or created Chris@0: */ Chris@0: public function save($filename) Chris@0: { Chris@0: $json = []; Chris@0: foreach ($this as $cookie) { Chris@0: /** @var SetCookie $cookie */ Chris@0: if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) { Chris@0: $json[] = $cookie->toArray(); Chris@0: } Chris@0: } Chris@0: Chris@0: $jsonStr = \GuzzleHttp\json_encode($json); Chris@0: if (false === file_put_contents($filename, $jsonStr)) { Chris@0: throw new \RuntimeException("Unable to save file {$filename}"); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Load cookies from a JSON formatted file. Chris@0: * Chris@0: * Old cookies are kept unless overwritten by newly loaded ones. Chris@0: * Chris@0: * @param string $filename Cookie file to load. Chris@0: * @throws \RuntimeException if the file cannot be loaded. Chris@0: */ Chris@0: public function load($filename) Chris@0: { Chris@0: $json = file_get_contents($filename); Chris@0: if (false === $json) { Chris@0: throw new \RuntimeException("Unable to load file {$filename}"); Chris@0: } elseif ($json === '') { Chris@0: return; Chris@0: } Chris@0: Chris@0: $data = \GuzzleHttp\json_decode($json, true); Chris@0: if (is_array($data)) { Chris@0: foreach (json_decode($json, true) as $cookie) { Chris@0: $this->setCookie(new SetCookie($cookie)); Chris@0: } Chris@0: } elseif (strlen($data)) { Chris@0: throw new \RuntimeException("Invalid cookie file: {$filename}"); Chris@0: } Chris@0: } Chris@0: }