diff --git a/src/Assets/Cache.php b/src/Assets/Cache.php index 7df8dbbd4..cd5009279 100644 --- a/src/Assets/Cache.php +++ b/src/Assets/Cache.php @@ -34,6 +34,9 @@ class Cache implements CacheInterface /** @var string */ protected $cacheDir; + /** @var int */ + protected $duration = 31536000; + public function __construct(Builder $builder, string $pool = '') { $this->builder = $builder; @@ -53,6 +56,13 @@ public function get($key, $default = null): mixed return $default; } $data = unserialize($content); + + // check expiration + if ($data['expiration'] <= time()) { + $this->delete($key); + + return $default; + } } catch (\Exception $e) { $this->builder->getLogger()->error($e->getMessage()); @@ -71,7 +81,7 @@ public function set($key, $value, $ttl = null): bool $key = $this->prepareKey($key); $data = serialize([ 'value' => $value, - 'expiration' => time() + $ttl, + 'expiration' => time() + $this->duration($ttl), ]); $this->prune($key); Util\File::getFS()->dumpFile($this->getFilePathname($key), $data); @@ -269,4 +279,22 @@ private function prepareKey(string $key): string return $key; } + + /** + * Convert the various expressions of a TTL value into duration in seconds. + */ + protected function duration(\DateInterval|int|null $ttl): int + { + if ($ttl === null) { + return $this->duration; + } + if (is_int($ttl)) { + return $ttl; + } + if ($ttl instanceof \DateInterval) { + return (int)$ttl->format('%s'); + } + + throw new \InvalidArgumentException('TTL values must be one of null, int, \DateInterval'); + } }