FileCache.php 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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. if (\is_string($resetMark)) {
  38. $this->resetIfRequired($resetMark);
  39. }
  40. }
  41. /**
  42. * Получает данные из кэша по ключу
  43. */
  44. public function get($key, $default = null)
  45. {
  46. $file = $this->path($key);
  47. if (\is_file($file)) {
  48. require $file;
  49. if (
  50. isset($expire, $data)
  51. && (
  52. $expire < 1
  53. || $expire > \time()
  54. )
  55. ) {
  56. return $data;
  57. }
  58. }
  59. return $default;
  60. }
  61. /**
  62. * Устанавливает данные в кэш по ключу
  63. */
  64. public function set($key, $value, $ttl = null)
  65. {
  66. $file = $this->path($key);
  67. if ($ttl instanceof DateInterval) {
  68. $expire = (new DateTime('now', new DateTimeZone('UTC')))->add($value)->getTimestamp();
  69. } else {
  70. $expire = null === $ttl || $ttl < 1 ? 0 : \time() + $ttl;
  71. }
  72. $value = \var_export($value, true);
  73. $content = "<?php\n\n\$expire = {$expire};\n\n\$data = {$value};\n";
  74. if (false === \file_put_contents($file, $content, \LOCK_EX)) {
  75. return false;
  76. } else {
  77. $this->invalidate($file);
  78. return true;
  79. }
  80. }
  81. /**
  82. * Удаляет данные по ключу
  83. */
  84. public function delete($key)
  85. {
  86. $file = $this->path($key);
  87. if (
  88. \is_file($file)
  89. && ! \unlink($file)
  90. ) {
  91. return false;
  92. }
  93. $this->invalidate($file);
  94. return true;
  95. }
  96. /**
  97. * Очищает папку кэша от php файлов (рекурсивно)
  98. */
  99. public function clear()
  100. {
  101. $dir = new RecursiveDirectoryIterator($this->cacheDir, RecursiveDirectoryIterator::SKIP_DOTS);
  102. $iterator = new RecursiveIteratorIterator($dir);
  103. $files = new RegexIterator($iterator, '%\.php$%i', RegexIterator::MATCH);
  104. $result = true;
  105. foreach ($files as $file) {
  106. $result = \unlink($file->getPathname()) && $result;
  107. }
  108. return $result;
  109. }
  110. /**
  111. * Получает данные по списку ключей
  112. */
  113. public function getMultiple($keys, $default = null)
  114. {
  115. $this->validateIterable($keys);
  116. $result = [];
  117. foreach ($keys as $key) {
  118. $result[$key] = $this->get($key, $default);
  119. }
  120. return $result;
  121. }
  122. /**
  123. * Устанавливает данные в кэш по списку ключ => значение
  124. */
  125. public function setMultiple($values, $ttl = null)
  126. {
  127. $this->validateIterable($keys);
  128. $result = true;
  129. foreach ($values as $key => $value) {
  130. $result = $this->set($key, $value, $ttl) && $result;
  131. }
  132. return $result;
  133. }
  134. /**
  135. * Удаляет данные по списку ключей
  136. */
  137. public function deleteMultiple($keys)
  138. {
  139. $this->validateIterable($keys);
  140. $result = true;
  141. foreach ($keys as $key) {
  142. $result = $this->delete($key) && $result;
  143. }
  144. return $result;
  145. }
  146. /**
  147. * Проверяет кеш на наличие ключа
  148. */
  149. public function has($key)
  150. {
  151. $file = $this->path($key);
  152. if (\is_file($file)) {
  153. require $file;
  154. if (
  155. isset($expire, $data)
  156. && (
  157. $expire < 1
  158. || $expire > \time()
  159. )
  160. ) {
  161. return true;
  162. }
  163. }
  164. return false;
  165. }
  166. /**
  167. * Проверяет ключ
  168. * Генерирует путь до файла
  169. */
  170. protected function path($key): string
  171. {
  172. if (! \is_string($key)) {
  173. throw new InvalidArgumentException('Expects a string, got: ' . \gettype($key));
  174. }
  175. if (! \preg_match('%^[a-z0-9_\.]+$%Di', $key)) {
  176. throw new InvalidArgumentException('Key is not a legal value');
  177. }
  178. if ('poll' == \substr($key, 0, 4)) {
  179. return $this->cacheDir . "/polls/{$key}.php";
  180. } else {
  181. return $this->cacheDir . "/cache_{$key}.php";
  182. }
  183. }
  184. /**
  185. * Очищает opcache и apc от закэшированного файла
  186. */
  187. protected function invalidate(string $file): void
  188. {
  189. if (\function_exists('\\opcache_invalidate')) {
  190. \opcache_invalidate($file, true);
  191. } elseif (\function_exists('\\apc_delete_file')) {
  192. \apc_delete_file($file);
  193. }
  194. }
  195. /**
  196. * Проверяет, является ли переменная итерируемой
  197. */
  198. protected function validateIterable($iterable): void
  199. {
  200. if (! \is_iterable($iterable)) {
  201. throw new InvalidArgumentException('Expects a iterable, got: ' . \gettype($iterable));
  202. }
  203. }
  204. /**
  205. * Сбрасывает кеш при изменении $resetMark
  206. */
  207. protected function resetIfRequired(string $resetMark): void
  208. {
  209. if (empty($resetMark)) {
  210. return;
  211. }
  212. $hash = \sha1($resetMark);
  213. if ($this->get('reset_mark_hash') !== $hash) {
  214. $this->clear();
  215. $this->set('reset_mark_hash', $hash);
  216. }
  217. }
  218. }