Passed
Pull Request — master (#19827)
by Brandon
12:33
created

Cache   F

Complexity

Total Complexity 69

Size/Duplication

Total Lines 565
Duplicated Lines 0 %

Test Coverage

Coverage 78.79%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 127
c 1
b 0
f 0
dl 0
loc 565
ccs 104
cts 132
cp 0.7879
rs 2.88
wmc 69

22 Methods

Rating   Name   Duplication   Size   Complexity  
A offsetExists() 0 4 1
A buildKey() 0 15 5
A init() 0 4 1
A offsetGet() 0 4 1
B get() 0 22 9
A exists() 0 6 1
A add() 0 13 5
B multiSet() 0 23 7
A getOrSet() 0 12 3
A set() 0 17 6
B multiGet() 0 25 9
A madd() 0 3 1
A getValues() 0 8 2
A flush() 0 3 1
A setValues() 0 10 3
A multiAdd() 0 19 6
A mset() 0 3 1
A offsetUnset() 0 4 1
A delete() 0 5 1
A offsetSet() 0 4 1
A mget() 0 3 1
A addValues() 0 10 3

How to fix   Complexity   

Complex Class

Complex classes like Cache often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Cache, and based on these observations, apply Extract Interface, too.

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