RuntimeCache::get()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
nc 3
nop 2
dl 0
loc 15
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace RemotelyLiving\Doorkeeper\Utilities;
6
7
final class RuntimeCache
8
{
9
    /**
10
     * @var mixed[]
11
     */
12
    private $cache = [];
13
14
    private ?int $maxCacheItems;
15
16
    public function __construct(int $maxCacheItems = null)
17
    {
18
        $this->maxCacheItems = $maxCacheItems;
19
    }
20
21
    /**
22
     * @return mixed|null
23
     */
24
    public function get(string $key, callable $fallback = null)
25
    {
26
        if ($this->has($key)) {
27
            return $this->cache[$key];
28
        }
29
30
        if (!$fallback) {
31
            return null;
32
        }
33
34
        $result = $fallback();
35
36
        $this->set($key, $result);
37
38
        return $result;
39
    }
40
41
    public function has(string $key): bool
42
    {
43
        return isset($this->cache[$key]);
44
    }
45
46
    /**
47
     * @param mixed $value
48
     */
49
    public function set(string $key, $value): void
50
    {
51
        if ($this->maxCacheItems !== null && count($this->cache) >= $this->maxCacheItems) {
52
            array_shift($this->cache);
53
        }
54
55
        $this->cache[$key] = $value;
56
    }
57
58
    public function destroy(string $key): void
59
    {
60
        unset($this->cache[$key]);
61
    }
62
63
    public function flush(): void
64
    {
65
        $this->cache = [];
66
    }
67
}
68