Passed
Pull Request — master (#74)
by Alexander
02:13
created

Cache::evaluateDependency()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

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