Skip to content

Commit

Permalink
refactor: implement cache duration
Browse files Browse the repository at this point in the history
  • Loading branch information
ArnaudLigny committed Jan 13, 2025
1 parent 300f874 commit 3806bbd
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion src/Assets/Cache.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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());

Expand All @@ -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);
Expand Down Expand Up @@ -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) {

Check notice on line 294 in src/Assets/Cache.php

View check run for this annotation

Scrutinizer / Inspection

src/Assets/Cache.php#L294

``$ttl`` is always a sub-type of ``DateInterval``.
return (int)$ttl->format('%s');
}

throw new \InvalidArgumentException('TTL values must be one of null, int, \DateInterval');
}
}

0 comments on commit 3806bbd

Please sign in to comment.