cacheDir = $dir; } /** * Получение данных из кэша по ключу * * @param string $key * @param mixed $default * * @return mixed */ public function get($key, $default = null) { $file = $this->file($key); if (\is_file($file)) { require $file; if (isset($expire) && isset($data) && ($expire < 1 || $expire > \time()) ) { return $data; } } return $default; } /** * Установка данных в кэш по ключу * * @param string $key * @param mixed $value * @param int $ttl * * @throws RuntimeException * * @return bool */ public function set($key, $value, $ttl = null) { $file = $this->file($key); $expire = null === $ttl || $ttl < 1 ? 0 : \time() + $ttl; $content = "invalidate($file); return true; } } /** * Удаление данных по ключу * * @param string $key * * @throws RuntimeException * * @return bool */ public function delete($key) { $file = $this->file($key); if (\is_file($file)) { if (\unlink($file)) { $this->invalidate($file); return true; } else { throw new RuntimeException("The key `$key` could not be removed"); } } else { return true; } } /** * Очистка кэша * * @return bool */ public function clear() { $dir = new RecursiveDirectoryIterator($this->cacheDir, RecursiveDirectoryIterator::SKIP_DOTS); $iterator = new RecursiveIteratorIterator($dir); $files = new RegexIterator($iterator, '%\.php$%i', RegexIterator::MATCH); $result = true; foreach ($files as $file) { $result = \unlink($file->getPathname()) && $result; } return $result; } /** * Проверка наличия ключа * * @param string $key * * @return bool */ public function has($key) { return null !== $this->get($key); } /** * Генерация имени файла по ключу * * @param string $key * * @throws InvalidArgumentException * * @return string */ protected function file($key) { if (\is_string($key) && \preg_match('%^[a-z0-9_-]+$%Di', $key)) { return $this->cacheDir . '/cache_' . $key . '.php'; } throw new InvalidArgumentException("Key '$key' contains invalid characters."); } /** * Очистка opcache и apc от закэшированного файла * * @param string $file */ protected function invalidate($file) { if (\function_exists('opcache_invalidate')) { \opcache_invalidate($file, true); } elseif (\function_exists('apc_delete_file')) { \apc_delete_file($file); } } }