-
-
Notifications
You must be signed in to change notification settings - Fork 56
/
Cache.php
83 lines (60 loc) · 1.5 KB
/
Cache.php
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
79
80
81
82
83
<?php
namespace Spatie\Once;
use WeakMap;
class Cache
{
protected static self $cache;
protected WeakMap $values;
protected bool $enabled = true;
public static function getInstance(): static
{
if (! isset(static::$cache)) {
static::$cache = new static;
}
return static::$cache;
}
protected function __construct()
{
$this->values = new WeakMap();
}
public function has(object $object, string $backtraceHash): bool
{
if (! isset($this->values[$object])) {
return false;
}
return array_key_exists($backtraceHash, $this->values[$object]);
}
public function get($object, string $backtraceHash): mixed
{
return $this->values[$object][$backtraceHash];
}
public function set(object $object, string $backtraceHash, mixed $value): void
{
$cached = $this->values[$object] ?? [];
$cached[$backtraceHash] = $value;
$this->values[$object] = $cached;
}
public function forget(object $object): void
{
unset($this->values[$object]);
}
public function flush(): self
{
$this->values = new WeakMap();
return $this;
}
public function enable(): self
{
$this->enabled = true;
return $this;
}
public function disable(): self
{
$this->enabled = false;
return $this;
}
public function isEnabled(): bool
{
return $this->enabled;
}
}