Passed
Push — main ( b8a391...6cd664 )
by Daryl
02:38
created

ArrayCache::set()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
nc 2
nop 3
dl 0
loc 7
ccs 5
cts 5
cp 1
crap 2
rs 10
c 1
b 0
f 0
1
<?php
2
3
namespace Clubdeuce\Tessitura\Cache;
4
5
use Clubdeuce\Tessitura\Interfaces\CacheInterface;
6
7
class ArrayCache implements CacheInterface
8
{
9
    private array $cache = [];
10
    private array $expiration = [];
11
12
    /**
13
     * Get a value from the cache.
14
     *
15
     * @param string $key The cache key
16
     * @return mixed|null The cached value or null if not found
17
     */
18 2
    public function get(string $key): mixed
19
    {
20 2
        if (!$this->has($key)) {
21 2
            return null;
22
        }
23
24
        // Check if expired
25 1
        if (isset($this->expiration[$key]) && $this->expiration[$key] < time()) {
26
            unset($this->cache[$key], $this->expiration[$key]);
27
            return null;
28
        }
29
30 1
        return $this->cache[$key];
31
    }
32
33
    /**
34
     * Set a value in the cache.
35
     *
36
     * @param string $key The cache key
37
     * @param mixed $value The value to cache
38
     * @param int $ttl Time to live in seconds
39
     * @return bool True on success, false on failure
40
     */
41 2
    public function set(string $key, mixed $value, int $ttl = 3600): bool
42
    {
43 2
        $this->cache[$key] = $value;
44 2
        if ($ttl > 0) {
45 2
            $this->expiration[$key] = time() + $ttl;
46
        }
47 2
        return true;
48
    }
49
50
    /**
51
     * Check if a key exists in the cache.
52
     *
53
     * @param string $key The cache key
54
     * @return bool True if the key exists, false otherwise
55
     */
56 2
    public function has(string $key): bool
57
    {
58 2
        if (!array_key_exists($key, $this->cache)) {
59 2
            return false;
60
        }
61
        
62
        // Check if expired
63 1
        if (isset($this->expiration[$key]) && $this->expiration[$key] < time()) {
64
            unset($this->cache[$key], $this->expiration[$key]);
65
            return false;
66
        }
67
        
68 1
        return true;
69
    }
70
71
    /**
72
     * Delete a value from the cache.
73
     *
74
     * @param string $key The cache key
75
     * @return bool True on success, false on failure
76
     */
77
    public function delete(string $key): bool
78
    {
79
        unset($this->cache[$key], $this->expiration[$key]);
80
        return true;
81
    }
82
83
    /**
84
     * Clear all cached values.
85
     *
86
     * @return bool True on success, false on failure
87
     */
88
    public function clear(): bool
89
    {
90
        $this->cache = [];
91
        $this->expiration = [];
92
        return true;
93
    }
94
}