MemoryAdapter::delete()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace IQParts\Cache\Adapter;
5
6
final class MemoryAdapter implements CacheAdapterInterface
7
{
8
    /**
9
     * @var array
10
     */
11
    private $data = [];
12
    /**
13
     * @var array
14
     */
15
    private $timeToLive = [];
16
17
    /**
18
     * @param string $key
19
     * @return mixed
20
     */
21
    public function get(string $key)
22
    {
23
        if (!isset($this->data[$key])) {
24
            return null;
25
        }
26
27
        if (!isset($this->timeToLive[$key])) {
28
            return $this->data[$key];
29
        }
30
31
        if ($this->ttl($key) > 0) {
32
            return $this->data[$key];
33
        }
34
35
        unset($this->timeToLive[$key], $this->data[$key]);
36
        return null;
37
    }
38
39
    /**
40
     * @param string $key
41
     * @param $value
42
     * @param int|null $ttl
43
     * @return void
44
     */
45
    public function set(string $key, $value, int $ttl = null): void
46
    {
47
        $this->data[$key] = $value;
48
        if ($ttl !== null) {
49
            $this->timeToLive[$key] = time() + $ttl;
50
        }
51
    }
52
53
    /**
54
     * @param string $key
55
     * @return void
56
     */
57
    public function delete(string $key): void
58
    {
59
        unset($this->data[$key], $this->timeToLive[$key]);
60
    }
61
62
    /**
63
     * @param string $key
64
     * @return mixed
65
     */
66
    public function keys($key = '*')
67
    {
68
        $matches = [];
69
        foreach ($this->data as $name => $value) {
70
            if (fnmatch($key, $name)) {
71
                $matches[] = $name;
72
            }
73
        }
74
        return $matches;
75
    }
76
77
    /**
78
     * @param $key
79
     * @return int
80
     */
81
    public function ttl($key): int
82
    {
83
        if (isset($this->timeToLive[$key])) {
84
            return max($this->timeToLive[$key] - time(), 0);
85
        }
86
        return self::NO_TTL;
87
    }
88
}