Passed
Push — master ( 9742c9...0c0f23 )
by Juuso
03:29 queued 56s
created

CacheMap::clear()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leinonen\DataLoader;
6
7
final class CacheMap implements CacheMapInterface, \Countable
8
{
9
    /**
10
     * @var array
11
     */
12
    private $cache = [];
13
14
    /**
15
     * {@inheritdoc}
16
     */
17
    public function get($key)
18
    {
19
        $index = $this->findCacheIndexByKey($key);
20
21
        if ($index === null) {
22
            return false;
23
        }
24
25
        return $this->cache[$index]['value'];
26
    }
27
28
    /**
29
     * {@inheritdoc}
30
     */
31
    public function set($key, $value): void
32
    {
33
        $cacheEntry = [
34
            'key' => $key,
35
            'value' => $value,
36
        ];
37
        $index = $this->findCacheIndexByKey($key);
38
39
        if ($index !== null) {
40
            $this->cache[$index] = $cacheEntry;
41
42
            return;
43
        }
44
45
        $this->cache[] = $cacheEntry;
46
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51
    public function delete($key): void
52
    {
53
        $index = $this->findCacheIndexByKey($key);
54
        unset($this->cache[$index]);
55
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60
    public function clear(): void
61
    {
62
        $this->cache = [];
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68
    public function count(): int
69
    {
70
        return \count($this->cache);
71
    }
72
73
    /**
74
     * Returns the index of the value from the cache array with the given key.
75
     *
76
     * @param mixed $cacheKey
77
     *
78
     * @return mixed
79
     */
80
    private function findCacheIndexByKey($cacheKey)
81
    {
82
        foreach ($this->cache as $index => $data) {
83
            if ($data['key'] === $cacheKey) {
84
                return $index;
85
            }
86
        }
87
    }
88
}
89