説明なし

FileCookieJar.php 2.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace GuzzleHttp\Cookie;
  3. /**
  4. * Persists non-session cookies using a JSON formatted file
  5. */
  6. class FileCookieJar extends CookieJar
  7. {
  8. /** @var string filename */
  9. private $filename;
  10. /** @var bool Control whether to presist session cookies or not. */
  11. private $storeSessionCookies;
  12. /**
  13. * Create a new FileCookieJar object
  14. *
  15. * @param string $cookieFile File to store the cookie data
  16. * @param bool $storeSessionCookies Set to true to store session cookies
  17. * in the cookie jar.
  18. *
  19. * @throws \RuntimeException if the file cannot be found or created
  20. */
  21. public function __construct($cookieFile, $storeSessionCookies = false)
  22. {
  23. $this->filename = $cookieFile;
  24. $this->storeSessionCookies = $storeSessionCookies;
  25. if (file_exists($cookieFile)) {
  26. $this->load($cookieFile);
  27. }
  28. }
  29. /**
  30. * Saves the file when shutting down
  31. */
  32. public function __destruct()
  33. {
  34. $this->save($this->filename);
  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 (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
  48. $json[] = $cookie->toArray();
  49. }
  50. }
  51. if (false === file_put_contents($filename, json_encode($json))) {
  52. throw new \RuntimeException("Unable to save file {$filename}");
  53. }
  54. }
  55. /**
  56. * Load cookies from a JSON formatted file.
  57. *
  58. * Old cookies are kept unless overwritten by newly loaded ones.
  59. *
  60. * @param string $filename Cookie file to load.
  61. * @throws \RuntimeException if the file cannot be loaded.
  62. */
  63. public function load($filename)
  64. {
  65. $json = file_get_contents($filename);
  66. if (false === $json) {
  67. throw new \RuntimeException("Unable to load file {$filename}");
  68. }
  69. $data = json_decode($json, true);
  70. if (is_array($data)) {
  71. foreach (json_decode($json, true) as $cookie) {
  72. $this->setCookie(new SetCookie($cookie));
  73. }
  74. } elseif (strlen($data)) {
  75. throw new \RuntimeException("Invalid cookie file: {$filename}");
  76. }
  77. }
  78. }