Lines 92.85% 26 / 28
Functions and Methods 80.00% 4 / 5
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
ArrayDriver 92.85% 26 / 28 80.00% 4 / 5 13.06 0.00% 0 / 1
 get 75.00% 6 / 8 0.00% 0 / 1 4.25
 set 100.00% 7 / 7 100.00% 1 / 1 3
 delete 100.00% 3 / 3 100.00% 1 / 1 1
 clear 100.00% 2 / 2 100.00% 1 / 1 1
 has 100.00% 8 / 8 100.00% 1 / 1 4
1<?php
2declare(strict_types=1);
3
4
5namespace Lucent\Cache\Drivers;
6
7use DateInterval;
8use Lucent\Cache\Cache;
9
10/**
11 * In-memory cache driver.
12 *
13 * Stores values in a plain array for the lifetime of the process. Useful
14 * for tests and for short-lived request-scoped caching where persistence
15 * across requests is not required.
16 */
17class ArrayDriver extends Cache
18{
19    /**
20     * Stored values keyed by cache key.
21     *
22     * @var array<string, array{expires: int|null, value: mixed}>
23     */
24    private array $store = [];
25
26    /**
27     * @inheritDoc
28     */
29    public function get(string $key, mixed $default = null): mixed
30    {
31        $this->validateKey($key);
32
33        if (!array_key_exists($key, $this->store)) {
34            return $default;
35        }
36
37        $entry = $this->store[$key];
38
39        if ($entry['expires'] !== null && $entry['expires'] <= time()) {
40            unset($this->store[$key]);
41            return $default;
42        }
43
44        return $entry['value'];
45    }
46
47    /**
48     * @inheritDoc
49     */
50    public function set(string $key, mixed $value, null|int|DateInterval $ttl = null): bool
51    {
52        $this->validateKey($key);
53
54        $expires = $this->expiryFromTtl($this->resolveTtl($ttl));
55
56        if ($expires !== null && $expires <= time()) {
57            unset($this->store[$key]);
58            return true;
59        }
60
61        $this->store[$key] = ['expires' => $expires, 'value' => $value];
62
63        return true;
64    }
65
66    /**
67     * @inheritDoc
68     */
69    public function delete(string $key): bool
70    {
71        $this->validateKey($key);
72
73        unset($this->store[$key]);
74
75        return true;
76    }
77
78    /**
79     * @inheritDoc
80     */
81    public function clear(): bool
82    {
83        $this->store = [];
84
85        return true;
86    }
87
88    /**
89     * @inheritDoc
90     */
91    public function has(string $key): bool
92    {
93        $this->validateKey($key);
94
95        if (!array_key_exists($key, $this->store)) {
96            return false;
97        }
98
99        $entry = $this->store[$key];
100
101        if ($entry['expires'] !== null && $entry['expires'] <= time()) {
102            unset($this->store[$key]);
103            return false;
104        }
105
106        return true;
107    }
108}