| 1 | <?php |
||
| 7 | final class CacheMap implements CacheMapInterface, \Countable |
||
| 8 | { |
||
| 9 | private array $cache = []; |
||
|
|
|||
| 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 |