Passed
Pull Request — master (#19584)
by Basil
08:20
created

Cache::buildKey()   A

Complexity

Conditions 6
Paths 12

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 6.0493

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 10
c 1
b 0
f 0
nc 12
nop 1
dl 0
loc 17
ccs 8
cts 9
cp 0.8889
crap 6.0493
rs 9.2222
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|callable 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
     * Since 2.0.47 its allowed to use a closure function, this can be usefull when working with environment variables or
64
     * any dynamic calculated cache key. Keep in mind to use alphanumeric characters:
65
     *
66
     * ```php
67
     * 'cache' => [
68
     *     'class' => 'yii\caching\FileCache',
69
     *     'keyPrefix' => function() {
70
     *         return YII_ENV;
71
     *     }
72
     * ]
73
     * ```
74
     */
75
    public $keyPrefix;
76
    /**
77
     * @var array|null|false the functions used to serialize and unserialize cached data. Defaults to null, meaning
78
     * using the default PHP `serialize()` and `unserialize()` functions. If you want to use some more efficient
79
     * serializer (e.g. [igbinary](https://pecl.php.net/package/igbinary)), you may configure this property with
80
     * a two-element array. The first element specifies the serialization function, and the second the deserialization
81
     * function. If this property is set false, data will be directly sent to and retrieved from the underlying
82
     * cache component without any serialization or deserialization. You should not turn off serialization if
83
     * you are using [[Dependency|cache dependency]], because it relies on data serialization. Also, some
84
     * implementations of the cache can not correctly save and retrieve data different from a string type.
85
     */
86
    public $serializer;
87
    /**
88
     * @var int default duration in seconds before a cache entry will expire. Default value is 0, meaning infinity.
89
     * This value is used by [[set()]] if the duration is not explicitly given.
90
     * @since 2.0.11
91
     */
92
    public $defaultDuration = 0;
93
94
    /**
95
     * @var bool whether [igbinary serialization](https://pecl.php.net/package/igbinary) is available or not.
96
     */
97
    private $_igbinaryAvailable = false;
98
99
100
    /**
101
     * {@inheritdoc}
102
     */
103 270
    public function init()
104
    {
105 270
        parent::init();
106 270
        $this->_igbinaryAvailable = \extension_loaded('igbinary');
107 270
    }
108
109
    /**
110
     * Builds a normalized cache key from a given key.
111
     *
112
     * If the given key is a string containing alphanumeric characters only and no more than 32 characters,
113
     * then the key will be returned back prefixed with [[keyPrefix]]. Otherwise, a normalized key
114
     * is generated by serializing the given key, applying MD5 hashing, and prefixing with [[keyPrefix]].
115
     *
116
     * @param mixed $key the key to be normalized
117
     * @return string the generated cache key
118
     */
119 246
    public function buildKey($key)
120
    {
121 246
        if (is_string($key)) {
122 202
            $key = ctype_alnum($key) && StringHelper::byteLength($key) <= 32 ? $key : md5($key);
123
        } else {
124 74
            if ($this->_igbinaryAvailable) {
125
                $serializedKey = igbinary_serialize($key);
126
            } else {
127 74
                $serializedKey = serialize($key);
128
            }
129
130 74
            $key = md5($serializedKey);
131
        }
132
        
133 246
        $prefix = is_callable($this->keyPrefix) ? call_user_func($this->keyPrefix, $this) : $this->keyPrefix;
134
135 246
        return $prefix . $key;
0 ignored issues
show
Bug introduced by
Are you sure $prefix of type callable|mixed|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

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