1: <?php
2:
3: namespace Guzzle\Plugin\Cookie\CookieJar;
4:
5: use Guzzle\Common\Exception\RuntimeException;
6:
7: /**
8: * Persists non-session cookies using a JSON formatted file
9: */
10: class FileCookieJar extends ArrayCookieJar
11: {
12: /**
13: * @var string filename
14: */
15: protected $filename;
16:
17: /**
18: * Create a new FileCookieJar object
19: *
20: * @param string $cookieFile File to store the cookie data
21: *
22: * @throws RuntimeException if the file cannot be found or created
23: */
24: public function __construct($cookieFile)
25: {
26: $this->filename = $cookieFile;
27: $this->load();
28: }
29:
30: /**
31: * Saves the file when shutting down
32: */
33: public function __destruct()
34: {
35: $this->persist();
36: }
37:
38: /**
39: * Save the contents of the data array to the file
40: *
41: * @throws RuntimeException if the file cannot be found or created
42: */
43: protected function persist()
44: {
45: if (false === file_put_contents($this->filename, $this->serialize())) {
46: // @codeCoverageIgnoreStart
47: throw new RuntimeException('Unable to open file ' . $this->filename);
48: // @codeCoverageIgnoreEnd
49: }
50: }
51:
52: /**
53: * Load the contents of the json formatted file into the data array and discard any unsaved state
54: */
55: protected function load()
56: {
57: $json = file_get_contents($this->filename);
58: if (false === $json) {
59: // @codeCoverageIgnoreStart
60: throw new RuntimeException('Unable to open file ' . $this->filename);
61: // @codeCoverageIgnoreEnd
62: }
63:
64: $this->unserialize($json);
65: $this->cookies = $this->cookies ?: array();
66: }
67: }
68: