ClassBoundMemoryAdapter   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
eloc 9
c 1
b 0
f 0
dl 0
loc 36
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A set() 0 4 1
A __construct() 0 3 1
A get() 0 7 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace TheCodingMachine\CacheUtils;
6
7
use ReflectionClass;
8
9
/**
10
 * An adapter around a FileBoundCacheInterface that stores values in memory for the current request (for maximum performance)
11
 */
12
class ClassBoundMemoryAdapter implements ClassBoundCacheInterface
13
{
14
    /** @var array<string, mixed> */
15
    private $items;
16
    /** @var ClassBoundCacheInterface */
17
    private $classBoundCache;
18
19
    public function __construct(ClassBoundCacheInterface $classBoundCache)
20
    {
21
        $this->classBoundCache = $classBoundCache;
22
    }
23
24
    /**
25
     * Fetches an element from the cache by key.
26
     *
27
     * @return mixed
28
     */
29
    public function get(string $key)
30
    {
31
        if (isset($this->items[$key])) {
32
            return $this->items[$key];
33
        }
34
35
        return $this->items[$key] = $this->classBoundCache->get($key);
36
    }
37
38
    /**
39
     * Stores an item in the cache.
40
     *
41
     * @param mixed $item The item must be serializable.
42
     * @param ReflectionClass<object> $refClass If the class is modified, the cache item is invalidated.
43
     */
44
    public function set(string $key, $item, ReflectionClass $refClass, ?int $ttl = null): void
45
    {
46
        $this->items[$key] = $item;
47
        $this->classBoundCache->set($key, $item, $refClass, $ttl);
48
    }
49
}
50