-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathFreshCache.php
More file actions
78 lines (62 loc) · 1.85 KB
/
Copy pathFreshCache.php
File metadata and controls
78 lines (62 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
declare(strict_types=1);
namespace Typhoon\Reflection\Cache;
use Psr\SimpleCache\CacheInterface;
use Typhoon\Reflection\Internal\Data;
use Typhoon\TypedMap\TypedMap;
/**
* @api
*/
final class FreshCache implements CacheInterface
{
public function __construct(
private readonly CacheInterface $cache,
) {}
private static function isStale(mixed $value): bool
{
if (!$value instanceof TypedMap) {
return false;
}
$changeDetector = $value[Data::ChangeDetector] ?? null;
return $changeDetector !== null && $changeDetector->changed();
}
public function get(string $key, mixed $default = null): mixed
{
$value = $this->cache->get($key, $default);
return self::isStale($value) ? $default : $value;
}
public function set(string $key, mixed $value, null|\DateInterval|int $ttl = null): bool
{
return $this->cache->set($key, $value, $ttl);
}
public function delete(string $key): bool
{
return $this->cache->delete($key);
}
public function clear(): bool
{
return $this->cache->clear();
}
/**
* @param iterable<string> $keys
* @return \Generator<string, mixed>
*/
public function getMultiple(iterable $keys, mixed $default = null): iterable
{
foreach ($this->cache->getMultiple($keys) as $key => $value) {
yield $key => self::isStale($value) ? $default : $value;
}
}
public function setMultiple(iterable $values, null|\DateInterval|int $ttl = null): bool
{
return $this->cache->setMultiple($values, $ttl);
}
public function deleteMultiple(iterable $keys): bool
{
return $this->cache->deleteMultiple($keys);
}
public function has(string $key): bool
{
return $this->cache->get($key, $this) !== $this;
}
}