Passed
Push — master-to-2.2 ( 008205 )
by Paweł
09:46 queued 13s
created

Cache::offsetGet()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
ccs 2
cts 2
cp 1
cc 1
eloc 2
nc 1
nop 1
crap 1
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 81
    public function init()
92
    {
93 81
        parent::init();
94 81
        $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
        $data = $this->prepareCacheData($items, $dependency);
262
263 7
        return $this->setValues($data, $duration);
264
    }
265
266
    /**
267
     * Stores multiple items in cache. Each item contains a value identified by a key.
268
     * If the cache already contains such a key, the existing value and expiration time will be preserved.
269
     *
270
     * @param array $items the items to be cached, as key-value pairs.
271
     * @param int $duration default number of seconds in which the cached values will expire. 0 means never expire.
272
     * @param Dependency|null $dependency dependency of the cached items. If the dependency changes,
273
     * the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
274
     * This parameter is ignored if [[serializer]] is false.
275
     * @return array array of failed keys
276
     * @since 2.0.7
277
     */
278 2
    public function multiAdd($items, $duration = 0, $dependency = null)
279
    {
280 2
        $data = $this->prepareCacheData($items, $dependency);
281
282 2
        return $this->addValues($data, $duration);
283
    }
284
285
    /**
286
     * Prepares data for caching by serializing values and evaluating dependencies.
287
     *
288
     * @param array $items The items to be cached.
289
     * @param mixed $dependency The dependency to be evaluated.
290
     *
291
     * @return array The prepared data for caching.
292
     */
293 9
    private function prepareCacheData($items, $dependency)
294
    {
295 9
        if ($dependency !== null && $this->serializer !== false) {
296
            $dependency->evaluateDependency($this);
297
        }
298
299 9
        $data = [];
300 9
        foreach ($items as $key => $value) {
301 9
            if ($this->serializer === null) {
302 9
                $value = serialize([$value, $dependency]);
303
            } elseif ($this->serializer !== false) {
304
                $value = call_user_func($this->serializer[0], [$value, $dependency]);
305
            }
306
307 9
            $key = $this->buildKey($key);
308 9
            $data[$key] = $value;
309
        }
310
311 9
        return $data;
312
    }
313
314
    /**
315
     * Stores a value identified by a key into cache if the cache does not contain this key.
316
     * Nothing will be done if the cache already contains the key.
317
     * @param mixed $key a key identifying the value to be cached. This can be a simple string or
318
     * a complex data structure consisting of factors representing the key.
319
     * @param mixed $value the value to be cached
320
     * @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
321
     * @param Dependency|null $dependency dependency of the cached item. If the dependency changes,
322
     * the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
323
     * This parameter is ignored if [[serializer]] is false.
324
     * @return bool whether the value is successfully stored into cache
325
     */
326 4
    public function add($key, $value, $duration = 0, $dependency = null)
327
    {
328 4
        if ($dependency !== null && $this->serializer !== false) {
329
            $dependency->evaluateDependency($this);
330
        }
331 4
        if ($this->serializer === null) {
332 4
            $value = serialize([$value, $dependency]);
333
        } elseif ($this->serializer !== false) {
334
            $value = call_user_func($this->serializer[0], [$value, $dependency]);
335
        }
336 4
        $key = $this->buildKey($key);
337
338 4
        return $this->addValue($key, $value, $duration);
339
    }
340
341
    /**
342
     * Deletes a value with the specified key from cache.
343
     * @param mixed $key a key identifying the value to be deleted from cache. This can be a simple string or
344
     * a complex data structure consisting of factors representing the key.
345
     * @return bool if no error happens during deletion
346
     */
347 3
    public function delete($key)
348
    {
349 3
        $key = $this->buildKey($key);
350
351 3
        return $this->deleteValue($key);
352
    }
353
354
    /**
355
     * Deletes all values from cache.
356
     * Be careful of performing this operation if the cache is shared among multiple applications.
357
     * @return bool whether the flush operation was successful.
358
     */
359 23
    public function flush()
360
    {
361 23
        return $this->flushValues();
362
    }
363
364
    /**
365
     * Retrieves a value from cache with a specified key.
366
     * This method should be implemented by child classes to retrieve the data
367
     * from specific cache storage.
368
     * @param string $key a unique key identifying the cached value
369
     * @return mixed|false the value stored in cache, false if the value is not in the cache or expired. Most often
370
     * value is a string. If you have disabled [[serializer]], it could be something else.
371
     */
372
    abstract protected function getValue($key);
373
374
    /**
375
     * Stores a value identified by a key in cache.
376
     * This method should be implemented by child classes to store the data
377
     * in specific cache storage.
378
     * @param string $key the key identifying the value to be cached
379
     * @param mixed $value the value to be cached. Most often it's a string. If you have disabled [[serializer]],
380
     * it could be something else.
381
     * @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
382
     * @return bool true if the value is successfully stored into cache, false otherwise
383
     */
384
    abstract protected function setValue($key, $value, $duration);
385
386
    /**
387
     * Stores a value identified by a key into cache if the cache does not contain this key.
388
     * This method should be implemented by child classes to store the data
389
     * in specific cache storage.
390
     * @param string $key the key identifying the value to be cached
391
     * @param mixed $value the value to be cached. Most often it's a string. If you have disabled [[serializer]],
392
     * it could be something else.
393
     * @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
394
     * @return bool true if the value is successfully stored into cache, false otherwise
395
     */
396
    abstract protected function addValue($key, $value, $duration);
397
398
    /**
399
     * Deletes a value with the specified key from cache
400
     * This method should be implemented by child classes to delete the data from actual cache storage.
401
     * @param string $key the key of the value to be deleted
402
     * @return bool if no error happens during deletion
403
     */
404
    abstract protected function deleteValue($key);
405
406
    /**
407
     * Deletes all values from cache.
408
     * Child classes may implement this method to realize the flush operation.
409
     * @return bool whether the flush operation was successful.
410
     */
411
    abstract protected function flushValues();
412
413
    /**
414
     * Retrieves multiple values from cache with the specified keys.
415
     * The default implementation calls [[getValue()]] multiple times to retrieve
416
     * the cached values one by one. If the underlying cache storage supports multiget,
417
     * this method should be overridden to exploit that feature.
418
     * @param array $keys a list of keys identifying the cached values
419
     * @return array a list of cached values indexed by the keys
420
     */
421 5
    protected function getValues($keys)
422
    {
423 5
        $results = [];
424 5
        foreach ($keys as $key) {
425 5
            $results[$key] = $this->getValue($key);
426
        }
427
428 5
        return $results;
429
    }
430
431
    /**
432
     * Stores multiple key-value pairs in cache.
433
     * The default implementation calls [[setValue()]] multiple times store values one by one. If the underlying cache
434
     * storage supports multi-set, this method should be overridden to exploit that feature.
435
     * @param array $data array where key corresponds to cache key while value is the value stored
436
     * @param int $duration the number of seconds in which the cached values will expire. 0 means never expire.
437
     * @return array array of failed keys
438
     */
439 7
    protected function setValues($data, $duration)
440
    {
441 7
        $failedKeys = [];
442 7
        foreach ($data as $key => $value) {
443 7
            if ($this->setValue($key, $value, $duration) === false) {
444
                $failedKeys[] = $key;
445
            }
446
        }
447
448 7
        return $failedKeys;
449
    }
450
451
    /**
452
     * Adds multiple key-value pairs to cache.
453
     * The default implementation calls [[addValue()]] multiple times add values one by one. If the underlying cache
454
     * storage supports multi-add, this method should be overridden to exploit that feature.
455
     * @param array $data array where key corresponds to cache key while value is the value stored.
456
     * @param int $duration the number of seconds in which the cached values will expire. 0 means never expire.
457
     * @return array array of failed keys
458
     */
459 2
    protected function addValues($data, $duration)
460
    {
461 2
        $failedKeys = [];
462 2
        foreach ($data as $key => $value) {
463 2
            if ($this->addValue($key, $value, $duration) === false) {
464 2
                $failedKeys[] = $key;
465
            }
466
        }
467
468 2
        return $failedKeys;
469
    }
470
471
    /**
472
     * Returns whether there is a cache entry with a specified key.
473
     * This method is required by the interface [[\ArrayAccess]].
474
     * @param string $key a key identifying the cached value
475
     * @return bool
476
     */
477
    #[\ReturnTypeWillChange]
478
    public function offsetExists($key)
479
    {
480
        return $this->get($key) !== false;
481
    }
482
483
    /**
484
     * Retrieves the value from cache with a specified key.
485
     * This method is required by the interface [[\ArrayAccess]].
486
     * @param string $key a key identifying the cached value
487
     * @return mixed the value stored in cache, false if the value is not in the cache or expired.
488
     */
489 2
    #[\ReturnTypeWillChange]
490
    public function offsetGet($key)
491
    {
492 2
        return $this->get($key);
493
    }
494
495
    /**
496
     * Stores the value identified by a key into cache.
497
     * If the cache already contains such a key, the existing value will be
498
     * replaced with the new ones. To add expiration and dependencies, use the [[set()]] method.
499
     * This method is required by the interface [[\ArrayAccess]].
500
     * @param string $key the key identifying the value to be cached
501
     * @param mixed $value the value to be cached
502
     */
503 20
    #[\ReturnTypeWillChange]
504
    public function offsetSet($key, $value)
505
    {
506 20
        $this->set($key, $value);
507
    }
508
509
    /**
510
     * Deletes the value with the specified key from cache
511
     * This method is required by the interface [[\ArrayAccess]].
512
     * @param string $key the key of the value to be deleted
513
     */
514
    #[\ReturnTypeWillChange]
515
    public function offsetUnset($key)
516
    {
517
        $this->delete($key);
518
    }
519
520
    /**
521
     * Method combines both [[set()]] and [[get()]] methods to retrieve value identified by a $key,
522
     * or to store the result of $callable execution if there is no cache available for the $key.
523
     *
524
     * Usage example:
525
     *
526
     * ```php
527
     * public function getTopProducts($count = 10) {
528
     *     $cache = $this->cache; // Could be Yii::$app->cache
529
     *     return $cache->getOrSet(['top-n-products', 'n' => $count], function () use ($count) {
530
     *         return Products::find()->mostPopular()->limit($count)->all();
531
     *     }, 1000);
532
     * }
533
     * ```
534
     *
535
     * @param mixed $key a key identifying the value to be cached. This can be a simple string or
536
     * a complex data structure consisting of factors representing the key.
537
     * @param callable|\Closure $callable the callable or closure that will be used to generate a value to be cached.
538
     * If you use $callable that can return `false`, then keep in mind that [[getOrSet()]] may work inefficiently
539
     * because the [[yii\caching\Cache::get()]] method uses `false` return value to indicate the data item is not found
540
     * in the cache. Thus, caching of `false` value will lead to unnecessary internal calls.
541
     * @param int|null $duration default duration in seconds before the cache will expire. If not set,
542
     * [[defaultDuration]] value will be used.
543
     * @param Dependency|null $dependency dependency of the cached item. If the dependency changes,
544
     * the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
545
     * This parameter is ignored if [[serializer]] is `false`.
546
     * @return mixed result of $callable execution
547
     * @since 2.0.11
548
     */
549 4
    public function getOrSet($key, $callable, $duration = null, $dependency = null)
550
    {
551 4
        if (($value = $this->get($key)) !== false) {
552 2
            return $value;
553
        }
554
555 4
        $value = call_user_func($callable, $this);
556 4
        if (!$this->set($key, $value, $duration, $dependency)) {
557
            Yii::warning('Failed to set cache value for key ' . json_encode($key), __METHOD__);
558
        }
559
560 4
        return $value;
561
    }
562
}
563