source: externals/php/vendor/guzzlehttp/guzzle/src/Cookie/FileCookieJar.php@ b38cc03

Last change on this file since b38cc03 was 01a620f, checked in by Joachim Langenbach <joachim.langenbach@…>, 11 years ago

Removed submodules for php externals and use composer to provide them and versioned them afterwards

  • Property mode set to 100644
File size: 2.1 KB
Line 
1<?php
2namespace GuzzleHttp\Cookie;
3
4/**
5 * Persists non-session cookies using a JSON formatted file
6 */
7class FileCookieJar extends CookieJar
8{
9 /** @var string filename */
10 private $filename;
11
12 /**
13 * Create a new FileCookieJar object
14 *
15 * @param string $cookieFile File to store the cookie data
16 *
17 * @throws \RuntimeException if the file cannot be found or created
18 */
19 public function __construct($cookieFile)
20 {
21 $this->filename = $cookieFile;
22
23 if (file_exists($cookieFile)) {
24 $this->load($cookieFile);
25 }
26 }
27
28 /**
29 * Saves the file when shutting down
30 */
31 public function __destruct()
32 {
33 $this->save($this->filename);
34 }
35
36 /**
37 * Saves the cookies to a file.
38 *
39 * @param string $filename File to save
40 * @throws \RuntimeException if the file cannot be found or created
41 */
42 public function save($filename)
43 {
44 $json = [];
45 foreach ($this as $cookie) {
46 /** @var SetCookie $cookie */
47 if ($cookie->getExpires() && !$cookie->getDiscard()) {
48 $json[] = $cookie->toArray();
49 }
50 }
51
52 if (false === file_put_contents($filename, json_encode($json))) {
53 throw new \RuntimeException("Unable to save file {$filename}");
54 }
55 }
56
57 /**
58 * Load cookies from a JSON formatted file.
59 *
60 * Old cookies are kept unless overwritten by newly loaded ones.
61 *
62 * @param string $filename Cookie file to load.
63 * @throws \RuntimeException if the file cannot be loaded.
64 */
65 public function load($filename)
66 {
67 $json = file_get_contents($filename);
68 if (false === $json) {
69 throw new \RuntimeException("Unable to load file {$filename}");
70 }
71
72 $data = json_decode($json, true);
73 if (is_array($data)) {
74 foreach (json_decode($json, true) as $cookie) {
75 $this->setCookie(new SetCookie($cookie));
76 }
77 } elseif (strlen($data)) {
78 throw new \RuntimeException("Invalid cookie file: {$filename}");
79 }
80 }
81}
Note: See TracBrowser for help on using the repository browser.