ArrayCache::get()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 8
ccs 4
cts 4
cp 1
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Soupmix\Cache;
6
7
use DateInterval;
8
use DateTime;
9
use Psr\SimpleCache\CacheInterface;
10
11
use function array_key_exists;
12
use function time;
13 2
14
class ArrayCache extends Common implements CacheInterface
15 2
{
16 2
    private array $bucket = [];
17
18
    public function get($key, $default = null)
19 2
    {
20
        $this->checkReservedCharacters($key);
21
        if (! $this->has($key)) {
22 5
            return $default;
23
        }
24 5
25 3
        return $this->bucket[$key][0];
26 1
    }
27
28 3
    public function set($key, $value, $ttl = null): bool
29 2
    {
30
        $this->checkReservedCharacters($key);
31 3
        if ($ttl instanceof DateInterval) {
32 3
            $ttl = (new DateTime('now'))->add($ttl)->getTimeStamp() - time();
33
        }
34
35 2
        if ($ttl !== null) {
36
            $ttl = ((int) $ttl) + time();
37 2
        }
38 2
39 2
        $this->bucket[$key] = [$value, $ttl ?? false];
40 2
41
        return true;
42
    }
43
44
    public function delete($key): bool
45 6
    {
46
        $this->checkReservedCharacters($key);
47 6
        if (array_key_exists($key, $this->bucket)) {
48 6
            unset($this->bucket[$key]);
49
50
            return true;
51 3
        }
52
53 3
        return false;
54 3
    }
55 1
56
    public function clear(): bool
57 3
    {
58
        $this->bucket = [];
59
60
        return true;
61 3
    }
62
63
    public function has($key): bool
64
    {
65
        $this->checkReservedCharacters($key);
66
        if (! array_key_exists($key, $this->bucket)) {
67
            return false;
68
        }
69
70
        if ($this->bucket[$key][1] !== false && $this->bucket[$key][1] <= time()) {
71
            $this->delete($key);
72
73
            return false;
74
        }
75
76
        return true;
77
    }
78
}
79