fileManager = $fileManager; } /** * Whether is cached. */ public function has(string $key): bool { $cacheFile = $this->getCacheFile($key); return $this->fileManager->isFile($cacheFile); } /** * Get a stored value. * * @return array|stdClass */ public function get(string $key) { $cacheFile = $this->getCacheFile($key); return $this->fileManager->getPhpSafeContents($cacheFile); } /** * Store in cache. * * @param array|stdClass $data */ public function store(string $key, $data): void { /** @phpstan-var mixed $data */ if (!$this->checkDataIsValid($data)) { throw new InvalidArgumentException("Bad cache data type."); } $cacheFile = $this->getCacheFile($key); $result = $this->fileManager->putPhpContents($cacheFile, $data, true, true); if ($result === false) { throw new RuntimeException("Could not store '{$key}'."); } } /** * @param mixed $data * @return bool */ protected function checkDataIsValid($data) { $isInvalid = !is_array($data) && !$data instanceof stdClass; return !$isInvalid; } protected function getCacheFile(string $key): string { if ( $key === '' || preg_match('/[^a-zA-Z0-9_\/\-]/i', $key) || $key[0] === '/' || substr($key, -1) === '/' ) { throw new InvalidArgumentException("Bad cache key."); } return $this->cacheDir . $key . '.php'; } }