FileCache.php 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. <?php
  2. namespace ForkBB\Core\Cache;
  3. use Psr\SimpleCache\CacheInterface;
  4. use Psr\SimpleCache\CacheException;
  5. use Psr\SimpleCache\InvalidArgumentException;
  6. use DateInterval;
  7. use DateTime;
  8. use DateTimeZone;
  9. use RecursiveDirectoryIterator;
  10. use RecursiveIteratorIterator;
  11. use RegexIterator;
  12. class FileCache implements CacheInterface
  13. {
  14. /**
  15. * Директория кэша
  16. * @var string
  17. */
  18. protected $cacheDir;
  19. public function __construct(string $dir)
  20. {
  21. $dir = \rtrim($dir, '/');
  22. if (empty($dir)) {
  23. throw new CacheException('Cache directory unset');
  24. } elseif (! \is_dir($dir)) {
  25. throw new CacheException("Not a directory: {$dir}");
  26. } elseif (! \is_writable($dir)) {
  27. throw new CacheException("No write access to directory: {$dir}");
  28. }
  29. $this->cacheDir = $dir;
  30. }
  31. /**
  32. * Получает данные из кэша по ключу
  33. */
  34. public function get($key, $default = null)
  35. {
  36. $file = $this->path($key);
  37. if (\is_file($file)) {
  38. require $file;
  39. if (
  40. isset($expire, $data)
  41. && (
  42. $expire < 1
  43. || $expire > \time()
  44. )
  45. ) {
  46. return $data;
  47. }
  48. }
  49. return $default;
  50. }
  51. /**
  52. * Устанавливает данные в кэш по ключу
  53. */
  54. public function set($key, $value, $ttl = null)
  55. {
  56. $file = $this->path($key);
  57. if ($ttl instanceof DateInterval) {
  58. $expire = (new DateTime('now', new DateTimeZone('UTC')))->add($value)->getTimestamp();
  59. } else {
  60. $expire = null === $ttl || $ttl < 1 ? 0 : \time() + $ttl; //????
  61. }
  62. $value = \var_export($value, true);
  63. $content = "<?php\n\n\$expire = {$expire};\n\n\$data = {$value};\n";
  64. if (false === \file_put_contents($file, $content, \LOCK_EX)) {
  65. return false;
  66. } else {
  67. $this->invalidate($file);
  68. return true;
  69. }
  70. }
  71. /**
  72. * Удаляет данные по ключу
  73. */
  74. public function delete($key)
  75. {
  76. $file = $this->path($key);
  77. if (
  78. \is_file($file)
  79. && ! \unlink($file)
  80. ) {
  81. return false;
  82. }
  83. $this->invalidate($file);
  84. return true;
  85. }
  86. /**
  87. * Очищает папку кэша от php файлов (рекурсивно)
  88. */
  89. public function clear()
  90. {
  91. $dir = new RecursiveDirectoryIterator($this->cacheDir, RecursiveDirectoryIterator::SKIP_DOTS);
  92. $iterator = new RecursiveIteratorIterator($dir);
  93. $files = new RegexIterator($iterator, '%\.php$%i', RegexIterator::MATCH);
  94. $result = true;
  95. foreach ($files as $file) {
  96. $result = \unlink($file->getPathname()) && $result;
  97. }
  98. return $result;
  99. }
  100. /**
  101. * Получает данные по списку ключей
  102. */
  103. public function getMultiple($keys, $default = null)
  104. {
  105. $this->validateIterable($keys);
  106. $result = [];
  107. foreach ($keys as $key) {
  108. $result[$key] = $this->get($key, $default);
  109. }
  110. return $result;
  111. }
  112. /**
  113. * Устанавливает данные в кэш по списку ключ => значение
  114. */
  115. public function setMultiple($values, $ttl = null)
  116. {
  117. $this->validateIterable($keys);
  118. $result = true;
  119. foreach ($values as $key => $value) {
  120. $result = $this->set($key, $value, $ttl) && $result;
  121. }
  122. return $result;
  123. }
  124. /**
  125. * Удаляет данные по списку ключей
  126. */
  127. public function deleteMultiple($keys)
  128. {
  129. $this->validateIterable($keys);
  130. $result = true;
  131. foreach ($keys as $key) {
  132. $result = $this->delete($key) && $result;
  133. }
  134. return $result;
  135. }
  136. /**
  137. * Проверяет кеш на наличие ключа
  138. */
  139. public function has($key)
  140. {
  141. $file = $this->path($key);
  142. if (\is_file($file)) {
  143. require $file;
  144. if (
  145. isset($expire, $data)
  146. && (
  147. $expire < 1
  148. || $expire > \time()
  149. )
  150. ) {
  151. return true;
  152. }
  153. }
  154. return false;
  155. }
  156. /**
  157. * Проверяет ключ
  158. * Генерирует путь до файла
  159. */
  160. protected function path($key): string
  161. {
  162. if (! \is_string($key)) {
  163. throw new InvalidArgumentException('Expects a string, got: ' . \gettype($key));
  164. }
  165. if (! \preg_match('%^[a-z0-9_\.]+$%Di', $key)) {
  166. throw new InvalidArgumentException('Key is not a legal value');
  167. }
  168. return $this->cacheDir . "/cache_{$key}.php";
  169. }
  170. /**
  171. * Очищает opcache и apc от закэшированного файла
  172. */
  173. protected function invalidate(string $file): void
  174. {
  175. if (\function_exists('\\opcache_invalidate')) {
  176. \opcache_invalidate($file, true);
  177. } elseif (\function_exists('\\apc_delete_file')) {
  178. \apc_delete_file($file);
  179. }
  180. }
  181. /**
  182. * Проверяет, является ли переменная итерируемой
  183. */
  184. protected function validateIterable($iterable): void
  185. {
  186. if (! \is_iterable($iterable)) {
  187. throw new InvalidArgumentException('Expects a iterable, got: ' . \gettype($iterable));
  188. }
  189. }
  190. }