Completed
Push — master ( e1b391...0629e4 )
by David
14s queued 10s
created

ClassBoundMemoryAdapter::set()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 4
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 $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