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

Cache::iterableToArray()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 2
nc 2
nop 1
crap 2
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 The default TTL for a cache entry. null meaning infinity, negative or zero results in the
47
     * cache key deletion. This value is used by {@see getOrSet()}, if the duration is not explicitly given.
48
     */
49
    private ?int $defaultTtl;
50
51
    /**
52
     * @var string The string prefixed to every cache key so that it is unique globally in the whole cache storage.
53
     * It is recommended that you set a unique cache key prefix for each application if the same cache
54
     * storage is being used by different applications.
55
     */
56
    private string $keyPrefix;
57
58
    /**
59
     * @param \Psr\SimpleCache\CacheInterface $handler The actual cache handler.
60
     * @param DateInterval|int|null $defaultTtl The default TTL for a cache entry. null meaning infinity, negative or zero results in the
61
     * cache key deletion. This value is used by {@see getOrSet()}, if the duration is not explicitly given.
62
     * @param string $keyPrefix The string prefixed to every cache key so that it is unique globally in the whole cache storage.
63
     * It is recommended that you set a unique cache key prefix for each application if the same cache
64
     * storage is being used by different applications.
65
     */
66 57
    public function __construct(\Psr\SimpleCache\CacheInterface $handler, $defaultTtl = null, string $keyPrefix = '')
67
    {
68 57
        $this->handler = $handler;
69 57
        $this->items = new CacheItems();
70 57
        $this->defaultTtl = $this->normalizeTtl($defaultTtl);
71 51
        $this->keyPrefix = $keyPrefix;
72 51
    }
73
74 48
    public function getOrSet($key, callable $callable, $ttl = null, Dependency $dependency = null, float $beta = 1.0)
75
    {
76 48
        $key = $this->buildKey($key);
77 47
        $value = $this->getValue($key, $beta);
78
79 47
        return $value ?? $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" algorithm.
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->expired($key, $beta, $this->handler)) {
104 2
            return null;
105
        }
106
107 47
        $value = $this->handler->get($key);
108
109 47
        if (is_array($value) && isset($value[1]) && $value[1] instanceof CacheItem) {
110 5
            [$value, $item] = $value;
111
112 5
            if ($item->key() !== $key || $item->expired($beta, $this->handler)) {
113
                return null;
114
            }
115
116 5
            $this->items->set($item);
117
        }
118
119 47
        return $value;
120
    }
121
122
    /**
123
     * Sets the cache value and metadata, and returns the cache value.
124
     *
125
     * @param string $key The unique key of this item in the cache.
126
     * @param callable $callable The callable or closure that will be used to generate a value to be cached.
127
     * @param DateInterval|int|null $ttl The TTL of this value. If not set, default value is used.
128
     * @param Dependency|null $dependency The dependency of the cache value.
129
     *
130
     * @throws InvalidArgumentException Must be thrown if the `$key` or `$ttl` is not a legal value.
131
     * @throws SetCacheException Must be thrown if the data could not be set in the cache.
132
     *
133
     * @return mixed|null The cache value.
134
     */
135 47
    private function setAndGet(string $key, callable $callable, $ttl, ?Dependency $dependency)
136
    {
137 47
        $ttl = $this->normalizeTtl($ttl);
138 41
        $ttl ??= $this->defaultTtl;
139 41
        $value = $callable($this->handler);
140
141 41
        if ($dependency !== null) {
142 6
            $dependency->evaluateDependency($this->handler);
143
        }
144
145 41
        $item = new CacheItem($key, $ttl, $dependency);
146
147 41
        if (!$this->handler->set($key, [$value, $item], $ttl)) {
148 2
            throw new SetCacheException($key, $value, $item);
149
        }
150
151 39
        $this->items->set($item);
152 39
        return $value;
153
    }
154
155
    /**
156
     * Builds a normalized cache key from a given key by appending key prefix.
157
     *
158
     * @param mixed $key The key to be normalized.
159
     *
160
     * @return string The generated cache key.
161
     */
162 51
    private function buildKey($key): string
163
    {
164 51
        return $this->keyPrefix . $this->normalizeKey($key);
165
    }
166
167
    /**
168
     * Normalizes the cache key from a given key.
169
     *
170
     * If the given key is a string containing alphanumeric characters only and no more than 32 characters,
171
     * then the key will be returned back as it is, integers will be converted to strings. Otherwise,
172
     * a normalized key is generated by serializing the given key and applying MD5 hashing.
173
     *
174
     * @param mixed $key The key to be normalized.
175
     *
176
     * @throws InvalidArgumentException For invalid key.
177
     *
178
     * @return string The normalized cache key.
179
     */
180 51
    private function normalizeKey($key): string
181
    {
182 51
        if (is_string($key) || is_int($key)) {
183 33
            $key = (string) $key;
184 33
            return ctype_alnum($key) && mb_strlen($key, '8bit') <= 32 ? $key : md5($key);
185
        }
186
187 18
        if (($key = json_encode($key)) === false) {
188 2
            throw new InvalidArgumentException('Invalid key. ' . json_last_error_msg());
189
        }
190
191 16
        return md5($key);
192
    }
193
194
    /**
195
     * Normalizes cache TTL handling `null` value and {@see DateInterval} objects.
196
     *
197
     * @param mixed $ttl raw TTL.
198
     *
199
     * @throws InvalidArgumentException For invalid TTL.
200
     *
201
     * @return int|null TTL value as UNIX timestamp or null meaning infinity.
202
     */
203 57
    private function normalizeTtl($ttl): ?int
204
    {
205 57
        if ($ttl === null) {
206 51
            return null;
207
        }
208
209 19
        if ($ttl instanceof DateInterval) {
210 2
            return (new DateTime('@0'))->add($ttl)->getTimestamp();
211
        }
212
213 17
        if (is_int($ttl)) {
214 5
            return $ttl;
215
        }
216
217 12
        throw new InvalidArgumentException(sprintf(
218 12
            'Invalid TTL "%s" specified. It must be a \DateInterval instance, an integer, or null.',
219 12
            gettype($ttl),
220
        ));
221
    }
222
}
223