Passed
Pull Request — master (#75)
by Alexander
02:01
created

Cache::buildKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Cache;
6
7
use DateInterval;
8
use DateTime;
9
use Yiisoft\Cache\Dependency\Dependency;
10
use Yiisoft\Cache\Exception\InvalidArgumentException;
11
use Yiisoft\Cache\Exception\RemoveCacheException;
12
use Yiisoft\Cache\Exception\SetCacheException;
13
use Yiisoft\Cache\Metadata\CacheItem;
14
use Yiisoft\Cache\Metadata\CacheItems;
15
16
use function ctype_alnum;
17
use function gettype;
18
use function is_array;
19
use function is_int;
20
use function is_string;
21
use function json_encode;
22
use function json_last_error_msg;
23
use function mb_strlen;
24
use function md5;
25
26
/**
27
 * Cache provides support for the data caching, including cache key composition and dependencies, and uses
28
 * "Probably early expiration" for cache stampede prevention. The actual data caching is performed via
29
 * {@see Cache::$handler}, which should be configured to be {@see \Psr\SimpleCache\CacheInterface} instance.
30
 *
31
 * @see \Yiisoft\Cache\CacheInterface
32
 */
33
final class Cache implements CacheInterface
34
{
35
    /**
36
     * @var \Psr\SimpleCache\CacheInterface The actual cache handler.
37
     */
38
    private \Psr\SimpleCache\CacheInterface $handler;
39
40
    /**
41
     * @var CacheItems The items that store the metadata of each cache.
42
     */
43
    private CacheItems $items;
44
45
    /**
46
     * @var int|null
47
     */
48
    private ?int $defaultTtl;
49
50
    /**
51
     * @param \Psr\SimpleCache\CacheInterface $handler The actual cache handler.
52
     * @param DateInterval|int|null $defaultTtl The default TTL for a cache entry.
53
     * null meaning infinity, negative orzero results in the cache key deletion.
54
     * This value is used by {@see getOrSet()}, if the duration is not explicitly given.
55
     */
56 57
    public function __construct(\Psr\SimpleCache\CacheInterface $handler, $defaultTtl = null)
57
    {
58 57
        $this->handler = $handler;
59 57
        $this->items = new CacheItems();
60 57
        $this->defaultTtl = $this->normalizeTtl($defaultTtl);
61 51
    }
62
63 48
    public function getOrSet($key, callable $callable, $ttl = null, Dependency $dependency = null, float $beta = 1.0)
64
    {
65 48
        $key = $this->normalizeKey($key);
66 47
        $value = $this->getValue($key, $beta);
67
68 47
        return $value ?? $this->setAndGet($key, $callable, $ttl, $dependency);
69
    }
70
71 15
    public function remove($key): void
72
    {
73 15
        $key = $this->normalizeKey($key);
74
75 14
        if (!$this->handler->delete($key)) {
76 2
            throw new RemoveCacheException($key);
77
        }
78
79 12
        $this->items->remove($key);
80 12
    }
81
82
    /**
83
     * Gets the cache value.
84
     *
85
     * @param string $key The unique key of this item in the cache.
86
     * @param float $beta The value for calculating the range that is used for "Probably early expiration" algorithm.
87
     *
88
     * @return mixed|null The cache value or `null` if the cache is outdated or a dependency has been changed.
89
     */
90 47
    private function getValue(string $key, float $beta)
91
    {
92 47
        if ($this->items->expired($key, $beta, $this->handler)) {
93 2
            return null;
94
        }
95
96 47
        $value = $this->handler->get($key);
97
98 47
        if (is_array($value) && isset($value[1]) && $value[1] instanceof CacheItem) {
99 5
            [$value, $item] = $value;
100
101 5
            if ($item->key() !== $key || $item->expired($beta, $this->handler)) {
102
                return null;
103
            }
104
105 5
            $this->items->set($item);
106
        }
107
108 47
        return $value;
109
    }
110
111
    /**
112
     * Sets the cache value and metadata, and returns the cache value.
113
     *
114
     * @param string $key The unique key of this item in the cache.
115
     * @param callable $callable The callable or closure that will be used to generate a value to be cached.
116
     * @param DateInterval|int|null $ttl The TTL of this value. If not set, default value is used.
117
     * @param Dependency|null $dependency The dependency of the cache value.
118
     *
119
     * @throws InvalidArgumentException Must be thrown if the `$key` or `$ttl` is not a legal value.
120
     * @throws SetCacheException Must be thrown if the data could not be set in the cache.
121
     *
122
     * @return mixed|null The cache value.
123
     */
124 47
    private function setAndGet(string $key, callable $callable, $ttl, ?Dependency $dependency)
125
    {
126 47
        $ttl = $this->normalizeTtl($ttl);
127 41
        $ttl ??= $this->defaultTtl;
128 41
        $value = $callable($this->handler);
129
130 41
        if ($dependency !== null) {
131 6
            $dependency->evaluateDependency($this->handler);
132
        }
133
134 41
        $item = new CacheItem($key, $ttl, $dependency);
135
136 41
        if (!$this->handler->set($key, [$value, $item], $ttl)) {
137 2
            throw new SetCacheException($key, $value, $item);
138
        }
139
140 39
        $this->items->set($item);
141 39
        return $value;
142
    }
143
144
    /**
145
     * Normalizes the cache key from a given key.
146
     *
147
     * If the given key is a string containing alphanumeric characters only and no more than 32 characters,
148
     * then the key will be returned back as it is, integers will be converted to strings. Otherwise,
149
     * a normalized key is generated by serializing the given key and applying MD5 hashing.
150
     *
151
     * @param mixed $key The key to be normalized.
152
     *
153
     * @throws InvalidArgumentException For invalid key.
154
     *
155
     * @return string The normalized cache key.
156
     */
157 51
    private function normalizeKey($key): string
158
    {
159 51
        if (is_string($key) || is_int($key)) {
160 33
            $key = (string) $key;
161 33
            return ctype_alnum($key) && mb_strlen($key, '8bit') <= 32 ? $key : md5($key);
162
        }
163
164 18
        if (($key = json_encode($key)) === false) {
165 2
            throw new InvalidArgumentException('Invalid key. ' . json_last_error_msg());
166
        }
167
168 16
        return md5($key);
169
    }
170
171
    /**
172
     * Normalizes cache TTL handling `null` value and {@see DateInterval} objects.
173
     *
174
     * @param mixed $ttl raw TTL.
175
     *
176
     * @throws InvalidArgumentException For invalid TTL.
177
     *
178
     * @return int|null TTL value as UNIX timestamp or null meaning infinity.
179
     */
180 57
    private function normalizeTtl($ttl): ?int
181
    {
182 57
        if ($ttl === null) {
183 51
            return null;
184
        }
185
186 19
        if ($ttl instanceof DateInterval) {
187 2
            return (new DateTime('@0'))->add($ttl)->getTimestamp();
188
        }
189
190 17
        if (is_int($ttl)) {
191 5
            return $ttl;
192
        }
193
194 12
        throw new InvalidArgumentException(sprintf(
195 12
            'Invalid TTL "%s" specified. It must be a \DateInterval instance, an integer, or null.',
196 12
            gettype($ttl),
197
        ));
198
    }
199
}
200