1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
|
4
|
|
|
namespace TheCodingMachine\CacheUtils; |
5
|
|
|
|
6
|
|
|
|
7
|
|
|
use function array_merge; |
8
|
|
|
use ReflectionClass; |
9
|
|
|
|
10
|
|
|
class ClassBoundCache implements ClassBoundCacheInterface |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @var FileBoundCacheInterface |
14
|
|
|
*/ |
15
|
|
|
private $fileBoundCache; |
16
|
|
|
/** |
17
|
|
|
* @var bool |
18
|
|
|
*/ |
19
|
|
|
private $analyzeParentClasses; |
20
|
|
|
/** |
21
|
|
|
* @var bool |
22
|
|
|
*/ |
23
|
|
|
private $analyzeTraits; |
24
|
|
|
/** |
25
|
|
|
* @var bool |
26
|
|
|
*/ |
27
|
|
|
private $analyzeInterfaces; |
28
|
|
|
|
29
|
|
|
public function __construct(FileBoundCacheInterface $fileBoundCache, bool $analyzeParentClasses = true, bool $analyzeTraits = true, bool $analyzeInterfaces = false) |
30
|
|
|
{ |
31
|
|
|
$this->fileBoundCache = $fileBoundCache; |
32
|
|
|
$this->analyzeParentClasses = $analyzeParentClasses; |
33
|
|
|
$this->analyzeTraits = $analyzeTraits; |
34
|
|
|
$this->analyzeInterfaces = $analyzeInterfaces; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Fetches an element from the cache by key. |
39
|
|
|
* |
40
|
|
|
* @return mixed |
41
|
|
|
*/ |
42
|
|
|
public function get(string $key) |
43
|
|
|
{ |
44
|
|
|
return $this->fileBoundCache->get($key); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Stores an item in the cache. |
49
|
|
|
* |
50
|
|
|
* @param mixed $item The item must be serializable. |
51
|
|
|
* @param ReflectionClass $refClass If the class is modified, the cache item is invalidated. |
52
|
|
|
*/ |
53
|
|
|
public function set(string $key, $item, ReflectionClass $refClass, ?int $ttl = null): void |
54
|
|
|
{ |
55
|
|
|
$files = $this->getFilesForClass($refClass); |
56
|
|
|
|
57
|
|
|
$this->fileBoundCache->set($key, $item, $files, $ttl); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
private function getFilesForClass(ReflectionClass $refClass): array |
61
|
|
|
{ |
62
|
|
|
$files = []; |
63
|
|
|
$file = $refClass->getFileName(); |
64
|
|
|
if ($file !== false) { |
65
|
|
|
$files[] = $file; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
if ($this->analyzeParentClasses && $refClass->getParentClass() !== false) { |
69
|
|
|
$files = array_merge($files, $this->getFilesForClass($refClass->getParentClass())); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
if ($this->analyzeTraits) { |
73
|
|
|
foreach ($refClass->getTraits() as $trait) { |
74
|
|
|
$files = array_merge($files, $this->getFilesForClass($trait)); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
if ($this->analyzeInterfaces) { |
79
|
|
|
foreach ($refClass->getInterfaces() as $interface) { |
80
|
|
|
$files = array_merge($files, $this->getFilesForClass($interface)); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
return $files; |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|