Passed
Push — master ( 18334c...e1b391 )
by David
02:20
created

ClassBoundCache::get()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
c 0
b 0
f 0
rs 10
cc 1
nc 1
nop 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 $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
     * @return array<int, string>
54
     */
55
    private function getFilesForClass(ReflectionClass $refClass): array
56
    {
57
        $files = [];
58
        $file = $refClass->getFileName();
59
        if ($file !== false) {
60
            $files[] = $file;
61
        }
62
63
        if ($this->analyzeParentClasses && $refClass->getParentClass() !== false) {
64
            $files = array_merge($files, $this->getFilesForClass($refClass->getParentClass()));
65
        }
66
67
        if ($this->analyzeTraits) {
68
            foreach ($refClass->getTraits() as $trait) {
69
                $files = array_merge($files, $this->getFilesForClass($trait));
70
            }
71
        }
72
73
        if ($this->analyzeInterfaces) {
74
            foreach ($refClass->getInterfaces() as $interface) {
75
                $files = array_merge($files, $this->getFilesForClass($interface));
76
            }
77
        }
78
79
        return $files;
80
    }
81
}
82