FileCache.php 5.6 KB

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