FileCache.php 6.4 KB

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