FileCache.php 6.0 KB

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