Passed
Pull Request — master (#19892)
by
unknown
05:31
created

Cache::flush()   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
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://www.yiiframework.com/license/
6
 */
7
8
namespace yii\caching;
9
10
use Yii;
11
use yii\base\Component;
12
use yii\helpers\StringHelper;
13
14
/**
15
 * Cache is the base class for cache classes supporting different cache storage implementations.
16
 *
17
 * A data item can be stored in the cache by calling [[set()]] and be retrieved back
18
 * later (in the same or different request) by [[get()]]. In both operations,
19
 * a key identifying the data item is required. An expiration time and/or a [[Dependency|dependency]]
20
 * can also be specified when calling [[set()]]. If the data item expires or the dependency
21
 * changes at the time of calling [[get()]], the cache will return no data.
22
 *
23
 * A typical usage pattern of cache is like the following:
24
 *
25
 * ```php
26
 * $key = 'demo';
27
 * $data = $cache->get($key);
28
 * if ($data === false) {
29
 *     // ...generate $data here...
30
 *     $cache->set($key, $data, $duration, $dependency);
31
 * }
32
 * ```
33
 *
34
 * Because Cache implements the [[\ArrayAccess]] interface, it can be used like an array. For example,
35
 *
36
 * ```php
37
 * $cache['foo'] = 'some data';
38
 * echo $cache['foo'];
39
 * ```
40
 *
41
 * Derived classes should implement the following methods which do the actual cache storage operations:
42
 *
43
 * - [[getValue()]]: retrieve the value with a key (if any) from cache
44
 * - [[setValue()]]: store the value with a key into cache
45
 * - [[addValue()]]: store the value only if the cache does not have this key before
46
 * - [[deleteValue()]]: delete the value with the specified key from cache
47
 * - [[flushValues()]]: delete all values from cache
48
 *
49
 * For more details and usage information on Cache, see the [guide article on caching](guide:caching-overview).
50
 *
51
 * @author Qiang Xue <[email protected]>
52
 * @since 2.0
53
 */
54
abstract class Cache extends Component implements CacheInterface
55
{
56
    /**
57
     * @var string a string prefixed to every cache key so that it is unique globally in the whole cache storage.
58
     * It is recommended that you set a unique cache key prefix for each application if the same cache
59
     * storage is being used by different applications.
60
     *
61
     * To ensure interoperability, only alphanumeric characters should be used.
62
     */
63
    public $keyPrefix;
64
    /**
65
     * @var array|null|false the functions used to serialize and unserialize cached data. Defaults to null, meaning
66
     * using the default PHP `serialize()` and `unserialize()` functions. If you want to use some more efficient
67
     * serializer (e.g. [igbinary](https://pecl.php.net/package/igbinary)), you may configure this property with
68
     * a two-element array. The first element specifies the serialization function, and the second the deserialization
69
     * function. If this property is set false, data will be directly sent to and retrieved from the underlying
70
     * cache component without any serialization or deserialization. You should not turn off serialization if
71
     * you are using [[Dependency|cache dependency]], because it relies on data serialization. Also, some
72
     * implementations of the cache can not correctly save and retrieve data different from a string type.
73
     */
74
    public $serializer;
75
    /**
76
     * @var int default duration in seconds before a cache entry will expire. Default value is 0, meaning infinity.
77
     * This value is used by [[set()]] if the duration is not explicitly given.
78
     * @since 2.0.11
79
     */
80
    public $defaultDuration = 0;
81
82
    /**
83
     * @var bool whether [igbinary serialization](https://pecl.php.net/package/igbinary) is available or not.
84
     */
85
    private $_igbinaryAvailable = false;
86
87
88
    /**
89
     * {@inheritdoc}
90
     */
91 80
    public function init()
92
    {
93 80
        parent::init();
94 80
        $this->_igbinaryAvailable = \extension_loaded('igbinary');
95
    }
96
97
    /**
98
     * Builds a normalized cache key from a given key.
99
     *
100
     * If the given key is a string containing alphanumeric characters only and no more than 32 characters,
101
     * then the key will be returned back prefixed with [[keyPrefix]]. Otherwise, a normalized key
102
     * is generated by serializing the given key, applying MD5 hashing, and prefixing with [[keyPrefix]].
103
     *
104
     * @param mixed $key the key to be normalized
105
     * @return string the generated cache key
106
     */
107 66
    public function buildKey($key)
108
    {
109 66
        if (is_string($key)) {
110 36
            $key = ctype_alnum($key) && StringHelper::byteLength($key) <= 32 ? $key : md5($key);
111
        } else {
112 33
            if ($this->_igbinaryAvailable) {
113
                $serializedKey = igbinary_serialize($key);
114
            } else {
115 33
                $serializedKey = serialize($key);
116
            }
117
118 33
            $key = md5($serializedKey);
119
        }
120
121 66
        return $this->keyPrefix . $key;
122
    }
123
124
    /**
125
     * Retrieves a value from cache with a specified key.
126
     * @param mixed $key a key identifying the cached value. This can be a simple string or
127
     * a complex data structure consisting of factors representing the key.
128
     * @return mixed the value stored in cache, false if the value is not in the cache, expired,
129
     * or the dependency associated with the cached data has changed.
130
     */
131 61
    public function get($key)
132
    {
133 61
        $key = $this->buildKey($key);
134 61
        $value = $this->getValue($key);
135 61
        if ($value === false || $this->serializer === false) {
136 46
            return $value;
137 50
        } elseif ($this->serializer === null) {
138 50
            $value = unserialize((string)$value);
139
        } else {
140
            $value = call_user_func($this->serializer[1], $value);
141
        }
142 50
        if (is_array($value) && !($value[1] instanceof Dependency && $value[1]->isChanged($this))) {
143 50
            return $value[0];
144
        }
145
146 4
        return false;
147
    }
148
149
    /**
150
     * Checks whether a specified key exists in the cache.
151
     * This can be faster than getting the value from the cache if the data is big.
152
     * In case a cache does not support this feature natively, this method will try to simulate it
153
     * but has no performance improvement over getting it.
154
     * Note that this method does not check whether the dependency associated
155
     * with the cached data, if there is any, has changed. So a call to [[get]]
156
     * may return false while exists returns true.
157
     * @param mixed $key a key identifying the cached value. This can be a simple string or
158
     * a complex data structure consisting of factors representing the key.
159
     * @return bool true if a value exists in cache, false if the value is not in the cache or expired.
160
     */
161
    public function exists($key)
162
    {
163
        $key = $this->buildKey($key);
164
        $value = $this->getValue($key);
165
166
        return $value !== false;
167
    }
168
169
    /**
170
     * Retrieves multiple values from cache with the specified keys.
171
     * Some caches (such as memcache, apc) allow retrieving multiple cached values at the same time,
172
     * which may improve the performance. In case a cache does not support this feature natively,
173
     * this method will try to simulate it.
174
     * @param string[] $keys list of string keys identifying the cached values
175
     * @return array list of cached values corresponding to the specified keys. The array
176
     * is returned in terms of (key, value) pairs.
177
     * If a value is not cached or expired, the corresponding array value will be false.
178
     * @since 2.0.7
179
     */
180 5
    public function multiGet($keys)
181
    {
182 5
        $keyMap = [];
183 5
        foreach ($keys as $key) {
184 5
            $keyMap[$key] = $this->buildKey($key);
185
        }
186 5
        $values = $this->getValues(array_values($keyMap));
187 5
        $results = [];
188 5
        foreach ($keyMap as $key => $newKey) {
189 5
            $results[$key] = false;
190 5
            if (isset($values[$newKey])) {
191 5
                if ($this->serializer === false) {
192
                    $results[$key] = $values[$newKey];
193
                } else {
194 5
                    $value = $this->serializer === null ? unserialize($values[$newKey])
195
                        : call_user_func($this->serializer[1], $values[$newKey]);
196
197 5
                    if (is_array($value) && !($value[1] instanceof Dependency && $value[1]->isChanged($this))) {
198 5
                        $results[$key] = $value[0];
199
                    }
200
                }
201
            }
202
        }
203
204 5
        return $results;
205
    }
206
207
    /**
208
     * Stores a value identified by a key into cache.
209
     * If the cache already contains such a key, the existing value and
210
     * expiration time will be replaced with the new ones, respectively.
211
     *
212
     * @param mixed $key a key identifying the value to be cached. This can be a simple string or
213
     * a complex data structure consisting of factors representing the key.
214
     * @param mixed $value the value to be cached
215
     * @param int|null $duration default duration in seconds before the cache will expire. If not set,
216
     * default [[defaultDuration]] value is used.
217
     * @param Dependency|null $dependency dependency of the cached item. If the dependency changes,
218
     * the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
219
     * This parameter is ignored if [[serializer]] is false.
220
     * @return bool whether the value is successfully stored into cache
221
     */
222 56
    public function set($key, $value, $duration = null, $dependency = null)
223
    {
224 56
        if ($duration === null) {
225 28
            $duration = $this->defaultDuration;
226
        }
227
228 56
        if ($dependency !== null && $this->serializer !== false) {
229 4
            $dependency->evaluateDependency($this);
230
        }
231 56
        if ($this->serializer === null) {
232 56
            $value = serialize([$value, $dependency]);
233
        } elseif ($this->serializer !== false) {
234
            $value = call_user_func($this->serializer[0], [$value, $dependency]);
235
        }
236 56
        $key = $this->buildKey($key);
237
238 56
        return $this->setValue($key, $value, $duration);
239
    }
240
241
    /**
242
     * Stores multiple items in cache. Each item contains a value identified by a key.
243
     * If the cache already contains such a key, the existing value and
244
     * expiration time will be replaced with the new ones, respectively.
245
     *
246
     * @param array $items the items to be cached, as key-value pairs.
247
     * @param int|null $duration default duration in seconds before the cache will expire. If not set,
248
     * default [[defaultDuration]] value is used.
249
     * @param Dependency|null $dependency dependency of the cached items. If the dependency changes,
250
     * the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
251
     * This parameter is ignored if [[serializer]] is false.
252
     * @return array array of failed keys
253
     * @since 2.0.7
254
     */
255 7
    public function multiSet($items, $duration = null, $dependency = null)
256
    {
257 7
        if ($duration === null) {
258 3
            $duration = $this->defaultDuration;
259
        }
260
261 7
        if ($dependency !== null && $this->serializer !== false) {
262
            $dependency->evaluateDependency($this);
263
        }
264
265 7
        $data = [];
266 7
        foreach ($items as $key => $value) {
267 7
            if ($this->serializer === null) {
268 7
                $value = serialize([$value, $dependency]);
269
            } elseif ($this->serializer !== false) {
270
                $value = call_user_func($this->serializer[0], [$value, $dependency]);
271
            }
272
273 7
            $key = $this->buildKey($key);
274 7
            $data[$key] = $value;
275
        }
276
277 7
        return $this->setValues($data, $duration);
278
    }
279
280
    /**
281
     * Stores multiple items in cache. Each item contains a value identified by a key.
282
     * If the cache already contains such a key, the existing value and expiration time will be preserved.
283
     *
284
     * @param array $items the items to be cached, as key-value pairs.
285
     * @param int $duration default number of seconds in which the cached values will expire. 0 means never expire.
286
     * @param Dependency|null $dependency dependency of the cached items. If the dependency changes,
287
     * the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
288
     * This parameter is ignored if [[serializer]] is false.
289
     * @return array array of failed keys
290
     * @since 2.0.7
291
     */
292 2
    public function multiAdd($items, $duration = 0, $dependency = null)
293
    {
294 2
        if ($dependency !== null && $this->serializer !== false) {
295
            $dependency->evaluateDependency($this);
296
        }
297
298 2
        $data = [];
299 2
        foreach ($items as $key => $value) {
300 2
            if ($this->serializer === null) {
301 2
                $value = serialize([$value, $dependency]);
302
            } elseif ($this->serializer !== false) {
303
                $value = call_user_func($this->serializer[0], [$value, $dependency]);
304
            }
305
306 2
            $key = $this->buildKey($key);
307 2
            $data[$key] = $value;
308
        }
309
310 2
        return $this->addValues($data, $duration);
311
    }
312
313
    /**
314
     * Stores a value identified by a key into cache if the cache does not contain this key.
315
     * Nothing will be done if the cache already contains the key.
316
     * @param mixed $key a key identifying the value to be cached. This can be a simple string or
317
     * a complex data structure consisting of factors representing the key.
318
     * @param mixed $value the value to be cached
319
     * @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
320
     * @param Dependency|null $dependency dependency of the cached item. If the dependency changes,
321
     * the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
322
     * This parameter is ignored if [[serializer]] is false.
323
     * @return bool whether the value is successfully stored into cache
324
     */
325 4
    public function add($key, $value, $duration = 0, $dependency = null)
326
    {
327 4
        if ($dependency !== null && $this->serializer !== false) {
328
            $dependency->evaluateDependency($this);
329
        }
330 4
        if ($this->serializer === null) {
331 4
            $value = serialize([$value, $dependency]);
332
        } elseif ($this->serializer !== false) {
333
            $value = call_user_func($this->serializer[0], [$value, $dependency]);
334
        }
335 4
        $key = $this->buildKey($key);
336
337 4
        return $this->addValue($key, $value, $duration);
338
    }
339
340
    /**
341
     * Deletes a value with the specified key from cache.
342
     * @param mixed $key a key identifying the value to be deleted from cache. This can be a simple string or
343
     * a complex data structure consisting of factors representing the key.
344
     * @return bool if no error happens during deletion
345
     */
346 3
    public function delete($key)
347
    {
348 3
        $key = $this->buildKey($key);
349
350 3
        return $this->deleteValue($key);
351
    }
352
353
    /**
354
     * Deletes all values from cache.
355
     * Be careful of performing this operation if the cache is shared among multiple applications.
356
     * @return bool whether the flush operation was successful.
357
     */
358 23
    public function flush()
359
    {
360 23
        return $this->flushValues();
361
    }
362
363
    /**
364
     * Retrieves a value from cache with a specified key.
365
     * This method should be implemented by child classes to retrieve the data
366
     * from specific cache storage.
367
     * @param string $key a unique key identifying the cached value
368
     * @return mixed|false the value stored in cache, false if the value is not in the cache or expired. Most often
369
     * value is a string. If you have disabled [[serializer]], it could be something else.
370
     */
371
    abstract protected function getValue($key);
372
373
    /**
374
     * Stores a value identified by a key in cache.
375
     * This method should be implemented by child classes to store the data
376
     * in specific cache storage.
377
     * @param string $key the key identifying the value to be cached
378
     * @param mixed $value the value to be cached. Most often it's a string. If you have disabled [[serializer]],
379
     * it could be something else.
380
     * @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
381
     * @return bool true if the value is successfully stored into cache, false otherwise
382
     */
383
    abstract protected function setValue($key, $value, $duration);
384
385
    /**
386
     * Stores a value identified by a key into cache if the cache does not contain this key.
387
     * This method should be implemented by child classes to store the data
388
     * in specific cache storage.
389
     * @param string $key the key identifying the value to be cached
390
     * @param mixed $value the value to be cached. Most often it's a string. If you have disabled [[serializer]],
391
     * it could be something else.
392
     * @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
393
     * @return bool true if the value is successfully stored into cache, false otherwise
394
     */
395
    abstract protected function addValue($key, $value, $duration);
396
397
    /**
398
     * Deletes a value with the specified key from cache
399
     * This method should be implemented by child classes to delete the data from actual cache storage.
400
     * @param string $key the key of the value to be deleted
401
     * @return bool if no error happens during deletion
402
     */
403
    abstract protected function deleteValue($key);
404
405
    /**
406
     * Deletes all values from cache.
407
     * Child classes may implement this method to realize the flush operation.
408
     * @return bool whether the flush operation was successful.
409
     */
410
    abstract protected function flushValues();
411
412
    /**
413
     * Retrieves multiple values from cache with the specified keys.
414
     * The default implementation calls [[getValue()]] multiple times to retrieve
415
     * the cached values one by one. If the underlying cache storage supports multiget,
416
     * this method should be overridden to exploit that feature.
417
     * @param array $keys a list of keys identifying the cached values
418
     * @return array a list of cached values indexed by the keys
419
     */
420 5
    protected function getValues($keys)
421
    {
422 5
        $results = [];
423 5
        foreach ($keys as $key) {
424 5
            $results[$key] = $this->getValue($key);
425
        }
426
427 5
        return $results;
428
    }
429
430
    /**
431
     * Stores multiple key-value pairs in cache.
432
     * The default implementation calls [[setValue()]] multiple times store values one by one. If the underlying cache
433
     * storage supports multi-set, this method should be overridden to exploit that feature.
434
     * @param array $data array where key corresponds to cache key while value is the value stored
435
     * @param int $duration the number of seconds in which the cached values will expire. 0 means never expire.
436
     * @return array array of failed keys
437
     */
438 7
    protected function setValues($data, $duration)
439
    {
440 7
        $failedKeys = [];
441 7
        foreach ($data as $key => $value) {
442 7
            if ($this->setValue($key, $value, $duration) === false) {
443
                $failedKeys[] = $key;
444
            }
445
        }
446
447 7
        return $failedKeys;
448
    }
449
450
    /**
451
     * Adds multiple key-value pairs to cache.
452
     * The default implementation calls [[addValue()]] multiple times add values one by one. If the underlying cache
453
     * storage supports multi-add, this method should be overridden to exploit that feature.
454
     * @param array $data array where key corresponds to cache key while value is the value stored.
455
     * @param int $duration the number of seconds in which the cached values will expire. 0 means never expire.
456
     * @return array array of failed keys
457
     */
458 2
    protected function addValues($data, $duration)
459
    {
460 2
        $failedKeys = [];
461 2
        foreach ($data as $key => $value) {
462 2
            if ($this->addValue($key, $value, $duration) === false) {
463 2
                $failedKeys[] = $key;
464
            }
465
        }
466
467 2
        return $failedKeys;
468
    }
469
470
    /**
471
     * Returns whether there is a cache entry with a specified key.
472
     * This method is required by the interface [[\ArrayAccess]].
473
     * @param string $key a key identifying the cached value
474
     * @return bool
475
     */
476
    #[\ReturnTypeWillChange]
477
    public function offsetExists($key)
478
    {
479
        return $this->get($key) !== false;
480
    }
481
482
    /**
483
     * Retrieves the value from cache with a specified key.
484
     * This method is required by the interface [[\ArrayAccess]].
485
     * @param string $key a key identifying the cached value
486
     * @return mixed the value stored in cache, false if the value is not in the cache or expired.
487
     */
488 2
    #[\ReturnTypeWillChange]
489
    public function offsetGet($key)
490
    {
491 2
        return $this->get($key);
492
    }
493
494
    /**
495
     * Stores the value identified by a key into cache.
496
     * If the cache already contains such a key, the existing value will be
497
     * replaced with the new ones. To add expiration and dependencies, use the [[set()]] method.
498
     * This method is required by the interface [[\ArrayAccess]].
499
     * @param string $key the key identifying the value to be cached
500
     * @param mixed $value the value to be cached
501
     */
502 20
    #[\ReturnTypeWillChange]
503
    public function offsetSet($key, $value)
504
    {
505 20
        $this->set($key, $value);
506
    }
507
508
    /**
509
     * Deletes the value with the specified key from cache
510
     * This method is required by the interface [[\ArrayAccess]].
511
     * @param string $key the key of the value to be deleted
512
     */
513
    #[\ReturnTypeWillChange]
514
    public function offsetUnset($key)
515
    {
516
        $this->delete($key);
517
    }
518
519
    /**
520
     * Method combines both [[set()]] and [[get()]] methods to retrieve value identified by a $key,
521
     * or to store the result of $callable execution if there is no cache available for the $key.
522
     *
523
     * Usage example:
524
     *
525
     * ```php
526
     * public function getTopProducts($count = 10) {
527
     *     $cache = $this->cache; // Could be Yii::$app->cache
528
     *     return $cache->getOrSet(['top-n-products', 'n' => $count], function () use ($count) {
529
     *         return Products::find()->mostPopular()->limit($count)->all();
530
     *     }, 1000);
531
     * }
532
     * ```
533
     *
534
     * @param mixed $key a key identifying the value to be cached. This can be a simple string or
535
     * a complex data structure consisting of factors representing the key.
536
     * @param callable|\Closure $callable the callable or closure that will be used to generate a value to be cached.
537
     * If you use $callable that can return `false`, then keep in mind that [[getOrSet()]] may work inefficiently
538
     * because the [[yii\caching\Cache::get()]] method uses `false` return value to indicate the data item is not found
539
     * in the cache. Thus, caching of `false` value will lead to unnecessary internal calls.
540
     * @param int|null $duration default duration in seconds before the cache will expire. If not set,
541
     * [[defaultDuration]] value will be used.
542
     * @param Dependency|null $dependency dependency of the cached item. If the dependency changes,
543
     * the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
544
     * This parameter is ignored if [[serializer]] is `false`.
545
     * @return mixed result of $callable execution
546
     * @since 2.0.11
547
     */
548 4
    public function getOrSet($key, $callable, $duration = null, $dependency = null)
549
    {
550 4
        if (($value = $this->get($key)) !== false) {
551 2
            return $value;
552
        }
553
554 4
        $value = call_user_func($callable, $this);
555 4
        if (!$this->set($key, $value, $duration, $dependency)) {
556
            Yii::warning('Failed to set cache value for key ' . json_encode($key), __METHOD__);
557
        }
558
559 4
        return $value;
560
    }
561
}
562