Passed
Push — master ( 0c0f23...09d191 )
by Juuso
02:11
created

CacheMap   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 82
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 0
dl 0
loc 82
ccs 28
cts 28
cp 1
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A set() 0 16 2
A findCacheIndexByKey() 0 8 3
A get() 0 10 2
A delete() 0 5 1
A clear() 0 4 1
A count() 0 4 1
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 35
    public function get($key)
18
    {
19 35
        $index = $this->findCacheIndexByKey($key);
20
21 35
        if ($index === null) {
22 32
            return false;
23
        }
24
25 14
        return $this->cache[$index]['value'];
26
    }
27
28
    /**
29
     * {@inheritdoc}
30
     */
31 35
    public function set($key, $value): void
32
    {
33
        $cacheEntry = [
34 35
            'key' => $key,
35 35
            'value' => $value,
36
        ];
37 35
        $index = $this->findCacheIndexByKey($key);
38
39 35
        if ($index !== null) {
40 1
            $this->cache[$index] = $cacheEntry;
41
42 1
            return;
43
        }
44
45 35
        $this->cache[] = $cacheEntry;
46 35
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51 13
    public function delete($key): void
52
    {
53 13
        $index = $this->findCacheIndexByKey($key);
54 13
        unset($this->cache[$index]);
55 13
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60 2
    public function clear(): void
61
    {
62 2
        $this->cache = [];
63 2
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68 2
    public function count(): int
69
    {
70 2
        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 37
    private function findCacheIndexByKey($cacheKey)
81
    {
82 37
        foreach ($this->cache as $index => $data) {
83 33
            if ($data['key'] === $cacheKey) {
84 33
                return $index;
85
            }
86
        }
87 37
    }
88
}
89