Passed
Push — upd ( 443b0a...b27e84 )
by
unknown
05:20
created

Cache::multiSet()   B

Complexity

Conditions 7
Paths 16

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

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