rss-bridge/caches/FileCache.php

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

113 lines
3.3 KiB
PHP
Raw Normal View History

2013-08-11 15:30:41 +04:00
<?php
declare(strict_types=1);
class FileCache implements CacheInterface
{
2023-09-21 23:05:55 +03:00
private Logger $logger;
private array $config;
2023-09-21 23:05:55 +03:00
public function __construct(
Logger $logger,
array $config = []
) {
$this->logger = $logger;
$default = [
'path' => null,
'enable_purge' => true,
];
$this->config = array_merge($default, $config);
if (!$this->config['path']) {
throw new \Exception('The FileCache needs a path value');
}
// Normalize with a single trailing slash
$this->config['path'] = rtrim($this->config['path'], '/') . '/';
}
public function get(string $key, $default = null)
{
$cacheFile = $this->createCacheFile($key);
if (!file_exists($cacheFile)) {
return $default;
}
$item = unserialize(file_get_contents($cacheFile));
if ($item === false) {
2023-09-21 23:05:55 +03:00
$this->logger->warning(sprintf('Failed to unserialize: %s', $cacheFile));
$this->delete($key);
return $default;
}
$expiration = $item['expiration'] ?? time();
if ($expiration === 0 || $expiration > time()) {
return $item['value'];
}
$this->delete($key);
return $default;
}
public function set($key, $value, int $ttl = null): void
{
$item = [
'key' => $key,
'value' => $value,
'expiration' => $ttl === null ? 0 : time() + $ttl,
];
$cacheFile = $this->createCacheFile($key);
$bytes = file_put_contents($cacheFile, serialize($item), LOCK_EX);
if ($bytes === false) {
// Consider just logging the error here
throw new \Exception(sprintf('Failed to write to: %s', $cacheFile));
}
}
public function delete(string $key): void
{
unlink($this->createCacheFile($key));
}
public function clear(): void
{
foreach (scandir($this->config['path']) as $filename) {
$cacheFile = $this->config['path'] . $filename;
$excluded = ['.' => true, '..' => true, '.gitkeep' => true];
if (isset($excluded[$filename]) || !is_file($cacheFile)) {
continue;
}
unlink($cacheFile);
}
}
public function prune(): void
{
if (! $this->config['enable_purge']) {
return;
}
foreach (scandir($this->config['path']) as $filename) {
$cacheFile = $this->config['path'] . $filename;
$excluded = ['.' => true, '..' => true, '.gitkeep' => true];
if (isset($excluded[$filename]) || !is_file($cacheFile)) {
continue;
}
$item = unserialize(file_get_contents($cacheFile));
if ($item === false) {
unlink($cacheFile);
continue;
}
$expiration = $item['expiration'] ?? time();
if ($expiration === 0 || $expiration > time()) {
continue;
}
unlink($cacheFile);
}
}
private function createCacheFile(string $key): string
{
return $this->config['path'] . hash('md5', $key) . '.cache';
}
public function getConfig()
{
return $this->config;
}
}