Completed
Push — php-74-ci ( 3d1af5...9001b7 )
by Alexander
24:14 queued 23:56
created

Cache::getValues()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 8
ccs 5
cts 5
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://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 null|array|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 277
    public function init()
92
    {
93 277
        parent::init();
94 277
        $this->_igbinaryAvailable = \extension_loaded('igbinary');
95 277
    }
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 260
    public function buildKey($key)
108
    {
109 260
        if (is_string($key)) {
110 217
            $key = ctype_alnum($key) && StringHelper::byteLength($key) <= 32 ? $key : md5($key);
111
        } else {
112 74
            if ($this->_igbinaryAvailable) {
113
                $serializedKey = igbinary_serialize($key);
114
            } else {
115 74
                $serializedKey = serialize($key);
116
            }
117
118 74
            $key = md5($serializedKey);
119
        }
120
121 260
        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 159
    public function get($key)
132
    {
133 159
        $key = $this->buildKey($key);
134 159
        $value = $this->getValue($key);
135 159
        if ($value === false || $this->serializer === false) {
136 122
            return $value;
137 101
        } elseif ($this->serializer === null) {
138 101
            $value = unserialize($value);
139
        } else {
140
            $value = call_user_func($this->serializer[1], $value);
141
        }
142 101
        if (is_array($value) && !($value[1] instanceof Dependency && $value[1]->isChanged($this))) {
143 100
            return $value[0];
144
        }
145
146 8
        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 1
    public function exists($key)
162
    {
163 1
        $key = $this->buildKey($key);
164 1
        $value = $this->getValue($key);
165
166 1
        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
     *
175
     * @param string[] $keys list of string keys identifying the cached values
176
     * @return array list of cached values corresponding to the specified keys. The array
177
     * is returned in terms of (key, value) pairs.
178
     * If a value is not cached or expired, the corresponding array value will be false.
179
     * @deprecated This method is an alias for [[multiGet()]] and will be removed in 2.1.0.
180
     */
181
    public function mget($keys)
182
    {
183
        return $this->multiGet($keys);
184
    }
185
186
    /**
187
     * Retrieves multiple values from cache with the specified keys.
188
     * Some caches (such as memcache, apc) allow retrieving multiple cached values at the same time,
189
     * which may improve the performance. In case a cache does not support this feature natively,
190
     * this method will try to simulate it.
191
     * @param string[] $keys list of string keys identifying the cached values
192
     * @return array list of cached values corresponding to the specified keys. The array
193
     * is returned in terms of (key, value) pairs.
194
     * If a value is not cached or expired, the corresponding array value will be false.
195
     * @since 2.0.7
196
     */
197 36
    public function multiGet($keys)
198
    {
199 36
        $keyMap = [];
200 36
        foreach ($keys as $key) {
201 36
            $keyMap[$key] = $this->buildKey($key);
202
        }
203 36
        $values = $this->getValues(array_values($keyMap));
204 36
        $results = [];
205 36
        foreach ($keyMap as $key => $newKey) {
206 36
            $results[$key] = false;
207 36
            if (isset($values[$newKey])) {
208 36
                if ($this->serializer === false) {
209
                    $results[$key] = $values[$newKey];
210
                } else {
211 36
                    $value = $this->serializer === null ? unserialize($values[$newKey])
212 36
                        : call_user_func($this->serializer[1], $values[$newKey]);
213
214 36
                    if (is_array($value) && !($value[1] instanceof Dependency && $value[1]->isChanged($this))) {
215 36
                        $results[$key] = $value[0];
216
                    }
217
                }
218
            }
219
        }
220
221 36
        return $results;
222
    }
223
224
    /**
225
     * Stores a value identified by a key into cache.
226
     * If the cache already contains such a key, the existing value and
227
     * expiration time will be replaced with the new ones, respectively.
228
     *
229
     * @param mixed $key a key identifying the value to be cached. This can be a simple string or
230
     * a complex data structure consisting of factors representing the key.
231
     * @param mixed $value the value to be cached
232
     * @param int $duration default duration in seconds before the cache will expire. If not set,
233
     * default [[defaultDuration]] value is used.
234
     * @param Dependency $dependency dependency of the cached item. If the dependency changes,
235
     * the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
236
     * This parameter is ignored if [[serializer]] is false.
237
     * @return bool whether the value is successfully stored into cache
238
     */
239 149
    public function set($key, $value, $duration = null, $dependency = null)
240
    {
241 149
        if ($duration === null) {
242 81
            $duration = $this->defaultDuration;
243
        }
244
245 149
        if ($dependency !== null && $this->serializer !== false) {
246 32
            $dependency->evaluateDependency($this);
247
        }
248 149
        if ($this->serializer === null) {
249 149
            $value = serialize([$value, $dependency]);
250
        } elseif ($this->serializer !== false) {
251
            $value = call_user_func($this->serializer[0], [$value, $dependency]);
252
        }
253 149
        $key = $this->buildKey($key);
254
255 149
        return $this->setValue($key, $value, $duration);
256
    }
257
258
    /**
259
     * Stores multiple items in cache. Each item contains a value identified by a key.
260
     * If the cache already contains such a key, the existing value and
261
     * expiration time will be replaced with the new ones, respectively.
262
     *
263
     * @param array $items the items to be cached, as key-value pairs.
264
     * @param int $duration default number of seconds in which the cached values will expire. 0 means never expire.
265
     * @param Dependency $dependency dependency of the cached items. If the dependency changes,
266
     * the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
267
     * This parameter is ignored if [[serializer]] is false.
268
     * @return array array of failed keys
269
     * @deprecated This method is an alias for [[multiSet()]] and will be removed in 2.1.0.
270
     */
271
    public function mset($items, $duration = 0, $dependency = null)
272
    {
273
        return $this->multiSet($items, $duration, $dependency);
274
    }
275
276
    /**
277
     * Stores multiple items in cache. Each item contains a value identified by a key.
278
     * If the cache already contains such a key, the existing value and
279
     * expiration time will be replaced with the new ones, respectively.
280
     *
281
     * @param array $items the items to be cached, as key-value pairs.
282
     * @param int $duration default number of seconds in which the cached values will expire. 0 means never expire.
283
     * @param Dependency $dependency dependency of the cached items. If the dependency changes,
284
     * the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
285
     * This parameter is ignored if [[serializer]] is false.
286
     * @return array array of failed keys
287
     * @since 2.0.7
288
     */
289 38
    public function multiSet($items, $duration = 0, $dependency = null)
290
    {
291 38
        if ($dependency !== null && $this->serializer !== false) {
292
            $dependency->evaluateDependency($this);
293
        }
294
295 38
        $data = [];
296 38
        foreach ($items as $key => $value) {
297 38
            if ($this->serializer === null) {
298 38
                $value = serialize([$value, $dependency]);
299
            } elseif ($this->serializer !== false) {
300
                $value = call_user_func($this->serializer[0], [$value, $dependency]);
301
            }
302
303 38
            $key = $this->buildKey($key);
304 38
            $data[$key] = $value;
305
        }
306
307 38
        return $this->setValues($data, $duration);
308
    }
309
310
    /**
311
     * Stores multiple items in cache. Each item contains a value identified by a key.
312
     * If the cache already contains such a key, the existing value and expiration time will be preserved.
313
     *
314
     * @param array $items the items to be cached, as key-value pairs.
315
     * @param int $duration default number of seconds in which the cached values will expire. 0 means never expire.
316
     * @param Dependency $dependency dependency of the cached items. If the dependency changes,
317
     * the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
318
     * This parameter is ignored if [[serializer]] is false.
319
     * @return array array of failed keys
320
     * @deprecated This method is an alias for [[multiAdd()]] and will be removed in 2.1.0.
321
     */
322
    public function madd($items, $duration = 0, $dependency = null)
323
    {
324
        return $this->multiAdd($items, $duration, $dependency);
325
    }
326
327
    /**
328
     * Stores multiple items in cache. Each item contains a value identified by a key.
329
     * If the cache already contains such a key, the existing value and expiration time will be preserved.
330
     *
331
     * @param array $items the items to be cached, as key-value pairs.
332
     * @param int $duration default number of seconds in which the cached values will expire. 0 means never expire.
333
     * @param Dependency $dependency dependency of the cached items. If the dependency changes,
334
     * the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
335
     * This parameter is ignored if [[serializer]] is false.
336
     * @return array array of failed keys
337
     * @since 2.0.7
338
     */
339 5
    public function multiAdd($items, $duration = 0, $dependency = null)
340
    {
341 5
        if ($dependency !== null && $this->serializer !== false) {
342
            $dependency->evaluateDependency($this);
343
        }
344
345 5
        $data = [];
346 5
        foreach ($items as $key => $value) {
347 5
            if ($this->serializer === null) {
348 5
                $value = serialize([$value, $dependency]);
349
            } elseif ($this->serializer !== false) {
350
                $value = call_user_func($this->serializer[0], [$value, $dependency]);
351
            }
352
353 5
            $key = $this->buildKey($key);
354 5
            $data[$key] = $value;
355
        }
356
357 5
        return $this->addValues($data, $duration);
358
    }
359
360
    /**
361
     * Stores a value identified by a key into cache if the cache does not contain this key.
362
     * Nothing will be done if the cache already contains the key.
363
     * @param mixed $key a key identifying the value to be cached. This can be a simple string or
364
     * a complex data structure consisting of factors representing the key.
365
     * @param mixed $value the value to be cached
366
     * @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
367
     * @param Dependency $dependency dependency of the cached item. If the dependency changes,
368
     * the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
369
     * This parameter is ignored if [[serializer]] is false.
370
     * @return bool whether the value is successfully stored into cache
371
     */
372 9
    public function add($key, $value, $duration = 0, $dependency = null)
373
    {
374 9
        if ($dependency !== null && $this->serializer !== false) {
375
            $dependency->evaluateDependency($this);
376
        }
377 9
        if ($this->serializer === null) {
378 9
            $value = serialize([$value, $dependency]);
379
        } elseif ($this->serializer !== false) {
380
            $value = call_user_func($this->serializer[0], [$value, $dependency]);
381
        }
382 9
        $key = $this->buildKey($key);
383
384 9
        return $this->addValue($key, $value, $duration);
385
    }
386
387
    /**
388
     * Deletes a value with the specified key from cache.
389
     * @param mixed $key a key identifying the value to be deleted from cache. This can be a simple string or
390
     * a complex data structure consisting of factors representing the key.
391
     * @return bool if no error happens during deletion
392
     */
393 131
    public function delete($key)
394
    {
395 131
        $key = $this->buildKey($key);
396
397 131
        return $this->deleteValue($key);
398
    }
399
400
    /**
401
     * Deletes all values from cache.
402
     * Be careful of performing this operation if the cache is shared among multiple applications.
403
     * @return bool whether the flush operation was successful.
404
     */
405 58
    public function flush()
406
    {
407 58
        return $this->flushValues();
408
    }
409
410
    /**
411
     * Retrieves a value from cache with a specified key.
412
     * This method should be implemented by child classes to retrieve the data
413
     * from specific cache storage.
414
     * @param string $key a unique key identifying the cached value
415
     * @return mixed|false the value stored in cache, false if the value is not in the cache or expired. Most often
416
     * value is a string. If you have disabled [[serializer]], it could be something else.
417
     */
418
    abstract protected function getValue($key);
419
420
    /**
421
     * Stores a value identified by a key in cache.
422
     * This method should be implemented by child classes to store the data
423
     * in specific cache storage.
424
     * @param string $key the key identifying the value to be cached
425
     * @param mixed $value the value to be cached. Most often it's a string. If you have disabled [[serializer]],
426
     * it could be something else.
427
     * @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
428
     * @return bool true if the value is successfully stored into cache, false otherwise
429
     */
430
    abstract protected function setValue($key, $value, $duration);
431
432
    /**
433
     * Stores a value identified by a key into cache if the cache does not contain this key.
434
     * This method should be implemented by child classes to store the data
435
     * in specific cache storage.
436
     * @param string $key the key identifying the value to be cached
437
     * @param mixed $value the value to be cached. Most often it's a string. If you have disabled [[serializer]],
438
     * it could be something else.
439
     * @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
440
     * @return bool true if the value is successfully stored into cache, false otherwise
441
     */
442
    abstract protected function addValue($key, $value, $duration);
443
444
    /**
445
     * Deletes a value with the specified key from cache
446
     * This method should be implemented by child classes to delete the data from actual cache storage.
447
     * @param string $key the key of the value to be deleted
448
     * @return bool if no error happens during deletion
449
     */
450
    abstract protected function deleteValue($key);
451
452
    /**
453
     * Deletes all values from cache.
454
     * Child classes may implement this method to realize the flush operation.
455
     * @return bool whether the flush operation was successful.
456
     */
457
    abstract protected function flushValues();
458
459
    /**
460
     * Retrieves multiple values from cache with the specified keys.
461
     * The default implementation calls [[getValue()]] multiple times to retrieve
462
     * the cached values one by one. If the underlying cache storage supports multiget,
463
     * this method should be overridden to exploit that feature.
464
     * @param array $keys a list of keys identifying the cached values
465
     * @return array a list of cached values indexed by the keys
466
     */
467 30
    protected function getValues($keys)
468
    {
469 30
        $results = [];
470 30
        foreach ($keys as $key) {
471 30
            $results[$key] = $this->getValue($key);
472
        }
473
474 30
        return $results;
475
    }
476
477
    /**
478
     * Stores multiple key-value pairs in cache.
479
     * The default implementation calls [[setValue()]] multiple times store values one by one. If the underlying cache
480
     * storage supports multi-set, this method should be overridden to exploit that feature.
481
     * @param array $data array where key corresponds to cache key while value is the value stored
482
     * @param int $duration the number of seconds in which the cached values will expire. 0 means never expire.
483
     * @return array array of failed keys
484
     */
485 35
    protected function setValues($data, $duration)
486
    {
487 35
        $failedKeys = [];
488 35
        foreach ($data as $key => $value) {
489 35
            if ($this->setValue($key, $value, $duration) === false) {
490
                $failedKeys[] = $key;
491
            }
492
        }
493
494 35
        return $failedKeys;
495
    }
496
497
    /**
498
     * Adds multiple key-value pairs to cache.
499
     * The default implementation calls [[addValue()]] multiple times add values one by one. If the underlying cache
500
     * storage supports multi-add, this method should be overridden to exploit that feature.
501
     * @param array $data array where key corresponds to cache key while value is the value stored.
502
     * @param int $duration the number of seconds in which the cached values will expire. 0 means never expire.
503
     * @return array array of failed keys
504
     */
505 5
    protected function addValues($data, $duration)
506
    {
507 5
        $failedKeys = [];
508 5
        foreach ($data as $key => $value) {
509 5
            if ($this->addValue($key, $value, $duration) === false) {
510 5
                $failedKeys[] = $key;
511
            }
512
        }
513
514 5
        return $failedKeys;
515
    }
516
517
    /**
518
     * Returns whether there is a cache entry with a specified key.
519
     * This method is required by the interface [[\ArrayAccess]].
520
     * @param string $key a key identifying the cached value
521
     * @return bool
522
     */
523
    public function offsetExists($key)
524
    {
525
        return $this->get($key) !== false;
526
    }
527
528
    /**
529
     * Retrieves the value from cache with a specified key.
530
     * This method is required by the interface [[\ArrayAccess]].
531
     * @param string $key a key identifying the cached value
532
     * @return mixed the value stored in cache, false if the value is not in the cache or expired.
533
     */
534 5
    public function offsetGet($key)
535
    {
536 5
        return $this->get($key);
537
    }
538
539
    /**
540
     * Stores the value identified by a key into cache.
541
     * If the cache already contains such a key, the existing value will be
542
     * replaced with the new ones. To add expiration and dependencies, use the [[set()]] method.
543
     * This method is required by the interface [[\ArrayAccess]].
544
     * @param string $key the key identifying the value to be cached
545
     * @param mixed $value the value to be cached
546
     */
547 50
    public function offsetSet($key, $value)
548
    {
549 50
        $this->set($key, $value);
550 50
    }
551
552
    /**
553
     * Deletes the value with the specified key from cache
554
     * This method is required by the interface [[\ArrayAccess]].
555
     * @param string $key the key of the value to be deleted
556
     */
557
    public function offsetUnset($key)
558
    {
559
        $this->delete($key);
560
    }
561
562
    /**
563
     * Method combines both [[set()]] and [[get()]] methods to retrieve value identified by a $key,
564
     * or to store the result of $callable execution if there is no cache available for the $key.
565
     *
566
     * Usage example:
567
     *
568
     * ```php
569
     * public function getTopProducts($count = 10) {
570
     *     $cache = $this->cache; // Could be Yii::$app->cache
571
     *     return $cache->getOrSet(['top-n-products', 'n' => $count], function () use ($count) {
572
     *         return Products::find()->mostPopular()->limit($count)->all();
573
     *     }, 1000);
574
     * }
575
     * ```
576
     *
577
     * @param mixed $key a key identifying the value to be cached. This can be a simple string or
578
     * a complex data structure consisting of factors representing the key.
579
     * @param callable|\Closure $callable the callable or closure that will be used to generate a value to be cached.
580
     * If you use $callable that can return `false`, then keep in mind that [[getOrSet()]] may work inefficiently
581
     * because the [[yii\caching\Cache::get()]] method uses `false` return value to indicate the data item is not found
582
     * in the cache. Thus, caching of `false` value will lead to unnecessary internal calls.
583
     * @param int $duration default duration in seconds before the cache will expire. If not set,
584
     * [[defaultDuration]] value will be used.
585
     * @param Dependency $dependency dependency of the cached item. If the dependency changes,
586
     * the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
587
     * This parameter is ignored if [[serializer]] is `false`.
588
     * @return mixed result of $callable execution
589
     * @since 2.0.11
590
     */
591 10
    public function getOrSet($key, $callable, $duration = null, $dependency = null)
592
    {
593 10
        if (($value = $this->get($key)) !== false) {
594 5
            return $value;
595
        }
596
597 10
        $value = call_user_func($callable, $this);
598 10
        if (!$this->set($key, $value, $duration, $dependency)) {
599
            Yii::warning('Failed to set cache value for key ' . json_encode($key), __METHOD__);
600
        }
601
602 10
        return $value;
603
    }
604
}
605