Test Failed
Push — master ( a0576a...ebf6f0 )
by Juuso
09:48 queued 11s
created

CacheMap::set()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 9
cts 9
cp 1
rs 9.7333
c 0
b 0
f 0
cc 2
nc 2
nop 2
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
    private array $cache = [];
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_ARRAY, expecting T_FUNCTION or T_CONST
Loading history...
10
11
    /**
12
     * {@inheritdoc}
13
     */
14
    public function get($key)
15
    {
16
        $index = $this->findCacheIndexByKey($key);
17 35
18
        if ($index === null) {
19 35
            return false;
20
        }
21 35
22 32
        return $this->cache[$index]['value'];
23
    }
24
25 14
    /**
26
     * {@inheritdoc}
27
     */
28
    public function set($key, $value): void
29
    {
30
        $cacheEntry = [
31 35
            'key' => $key,
32
            'value' => $value,
33
        ];
34 35
        $index = $this->findCacheIndexByKey($key);
35 35
36
        if ($index !== null) {
37 35
            $this->cache[$index] = $cacheEntry;
38
39 35
            return;
40 1
        }
41
42 1
        $this->cache[] = $cacheEntry;
43
    }
44
45 35
    /**
46 35
     * {@inheritdoc}
47
     */
48
    public function delete($key): void
49
    {
50
        $index = $this->findCacheIndexByKey($key);
51 13
        unset($this->cache[$index]);
52
    }
53 13
54 13
    /**
55 13
     * {@inheritdoc}
56
     */
57
    public function clear(): void
58
    {
59
        $this->cache = [];
60 2
    }
61
62 2
    /**
63 2
     * {@inheritdoc}
64
     */
65
    public function count(): int
66
    {
67
        return \count($this->cache);
68 2
    }
69
70 2
    /**
71
     * Returns the index of the value from the cache array with the given key.
72
     *
73
     * @param mixed $cacheKey
74
     *
75
     * @return mixed
76
     */
77
    private function findCacheIndexByKey($cacheKey)
78
    {
79
        foreach ($this->cache as $index => $data) {
80 37
            if ($data['key'] === $cacheKey) {
81
                return $index;
82 37
            }
83 33
        }
84 22
    }
85
}
86