ClassBoundCache   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 11
eloc 24
c 2
b 1
f 0
dl 0
loc 72
rs 10

4 Methods

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