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