Passed
Pull Request — master (#74)
by Evgeniy
02:06
created

Cache::prepareDataForSetOrAddMultiple()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

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