FilesystemCache.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. namespace Doctrine\Common\Cache;
  3. use const PHP_EOL;
  4. use function fclose;
  5. use function fgets;
  6. use function fopen;
  7. use function is_file;
  8. use function serialize;
  9. use function time;
  10. use function unserialize;
  11. /**
  12. * Filesystem cache driver.
  13. */
  14. class FilesystemCache extends FileCache
  15. {
  16. public const EXTENSION = '.doctrinecache.data';
  17. /**
  18. * {@inheritdoc}
  19. */
  20. public function __construct($directory, $extension = self::EXTENSION, $umask = 0002)
  21. {
  22. parent::__construct($directory, $extension, $umask);
  23. }
  24. /**
  25. * {@inheritdoc}
  26. */
  27. protected function doFetch($id)
  28. {
  29. $data = '';
  30. $lifetime = -1;
  31. $filename = $this->getFilename($id);
  32. if (! is_file($filename)) {
  33. return false;
  34. }
  35. $resource = fopen($filename, 'r');
  36. $line = fgets($resource);
  37. if ($line !== false) {
  38. $lifetime = (int) $line;
  39. }
  40. if ($lifetime !== 0 && $lifetime < time()) {
  41. fclose($resource);
  42. return false;
  43. }
  44. while (($line = fgets($resource)) !== false) {
  45. $data .= $line;
  46. }
  47. fclose($resource);
  48. return unserialize($data);
  49. }
  50. /**
  51. * {@inheritdoc}
  52. */
  53. protected function doContains($id)
  54. {
  55. $lifetime = -1;
  56. $filename = $this->getFilename($id);
  57. if (! is_file($filename)) {
  58. return false;
  59. }
  60. $resource = fopen($filename, 'r');
  61. $line = fgets($resource);
  62. if ($line !== false) {
  63. $lifetime = (int) $line;
  64. }
  65. fclose($resource);
  66. return $lifetime === 0 || $lifetime > time();
  67. }
  68. /**
  69. * {@inheritdoc}
  70. */
  71. protected function doSave($id, $data, $lifeTime = 0)
  72. {
  73. if ($lifeTime > 0) {
  74. $lifeTime = time() + $lifeTime;
  75. }
  76. $data = serialize($data);
  77. $filename = $this->getFilename($id);
  78. return $this->writeFile($filename, $lifeTime . PHP_EOL . $data);
  79. }
  80. }