Completed
Push — 2.1 ( b06332...7f8fdf )
by Dmitry
08:38
created

Cache::addValue()

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 1
c 0
b 0
f 0
ccs 0
cts 0
cp 0
nc 1
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\base\Component;
11
use yii\helpers\StringHelper;
12
13
/**
14
 * Cache is the base class for cache classes supporting different cache storage implementations.
15
 *
16
 * A data item can be stored in the cache by calling [[set()]] and be retrieved back
17
 * later (in the same or different request) by [[get()]]. In both operations,
18
 * a key identifying the data item is required. An expiration time and/or a [[Dependency|dependency]]
19
 * can also be specified when calling [[set()]]. If the data item expires or the dependency
20
 * changes at the time of calling [[get()]], the cache will return no data.
21
 *
22
 * A typical usage pattern of cache is like the following:
23
 *
24
 * ```php
25
 * $key = 'demo';
26
 * $data = $cache->get($key);
27
 * if ($data === false) {
28
 *     // ...generate $data here...
29
 *     $cache->set($key, $data, $duration, $dependency);
30
 * }
31
 * ```
32
 *
33
 * Because Cache implements the [[\ArrayAccess]] interface, it can be used like an array. For example,
34
 *
35
 * ```php
36
 * $cache['foo'] = 'some data';
37
 * echo $cache['foo'];
38
 * ```
39
 *
40
 * Derived classes should implement the following methods which do the actual cache storage operations:
41
 *
42
 * - [[getValue()]]: retrieve the value with a key (if any) from cache
43
 * - [[setValue()]]: store the value with a key into cache
44
 * - [[addValue()]]: store the value only if the cache does not have this key before
45
 * - [[deleteValue()]]: delete the value with the specified key from cache
46
 * - [[flushValues()]]: delete all values from cache
47
 *
48
 * For more details and usage information on Cache, see the [guide article on caching](guide:caching-overview).
49
 *
50
 * @author Qiang Xue <[email protected]>
51
 * @since 2.0
52
 */
53
abstract class Cache extends Component implements \ArrayAccess
54
{
55
    /**
56
     * @var string a string prefixed to every cache key so that it is unique globally in the whole cache storage.
57
     * It is recommended that you set a unique cache key prefix for each application if the same cache
58
     * storage is being used by different applications.
59
     *
60
     * To ensure interoperability, only alphanumeric characters should be used.
61
     */
62
    public $keyPrefix;
63
    /**
64
     * @var null|array|false the functions used to serialize and unserialize cached data. Defaults to null, meaning
65
     * using the default PHP `serialize()` and `unserialize()` functions. If you want to use some more efficient
66
     * serializer (e.g. [igbinary](http://pecl.php.net/package/igbinary)), you may configure this property with
67
     * a two-element array. The first element specifies the serialization function, and the second the deserialization
68
     * function. If this property is set false, data will be directly sent to and retrieved from the underlying
69
     * cache component without any serialization or deserialization. You should not turn off serialization if
70
     * you are using [[Dependency|cache dependency]], because it relies on data serialization. Also, some
71
     * implementations of the cache can not correctly save and retrieve data different from a string type.
72
     */
73
    public $serializer;
74
    /**
75
     * @var integer default duration in seconds before a cache entry will expire. Default value is 0, meaning infinity.
76
     * This value is used by [[set()]] if the duration is not explicitly given.
77
     * @since 2.0.11
78
     */
79
    public $defaultDuration = 0;
80
81
82
    /**
83
     * Builds a normalized cache key from a given key.
84
     *
85
     * If the given key is a string containing alphanumeric characters only and no more than 32 characters,
86
     * then the key will be returned back prefixed with [[keyPrefix]]. Otherwise, a normalized key
87
     * is generated by serializing the given key, applying MD5 hashing, and prefixing with [[keyPrefix]].
88
     *
89
     * @param mixed $key the key to be normalized
90
     * @return string the generated cache key
91
     */
92 113
    public function buildKey($key)
93
    {
94 113
        if (is_string($key)) {
95 106
            $key = ctype_alnum($key) && StringHelper::byteLength($key) <= 32 ? $key : md5($key);
96 106
        } else {
97 15
            $key = md5(json_encode($key));
98
        }
99
100 113
        return $this->keyPrefix . $key;
101
    }
102
103
    /**
104
     * Retrieves a value from cache with a specified key.
105
     * @param mixed $key a key identifying the cached value. This can be a simple string or
106
     * a complex data structure consisting of factors representing the key.
107
     * @return mixed the value stored in cache, false if the value is not in the cache, expired,
108
     * or the dependency associated with the cached data has changed.
109
     */
110 79
    public function get($key)
111
    {
112 79
        $key = $this->buildKey($key);
113 79
        $value = $this->getValue($key);
114 79
        if ($value === false || $this->serializer === false) {
115 46
            return $value;
116 60
        } elseif ($this->serializer === null) {
117 60
            $value = unserialize($value);
118 60
        } else {
119
            $value = call_user_func($this->serializer[1], $value);
120
        }
121 60
        if (is_array($value) && !($value[1] instanceof Dependency && $value[1]->isChanged($this))) {
122 59
            return $value[0];
123
        } else {
124 2
            return false;
125
        }
126
    }
127
128
    /**
129
     * Checks whether a specified key exists in the cache.
130
     * This can be faster than getting the value from the cache if the data is big.
131
     * In case a cache does not support this feature natively, this method will try to simulate it
132
     * but has no performance improvement over getting it.
133
     * Note that this method does not check whether the dependency associated
134
     * with the cached data, if there is any, has changed. So a call to [[get]]
135
     * may return false while exists returns true.
136
     * @param mixed $key a key identifying the cached value. This can be a simple string or
137
     * a complex data structure consisting of factors representing the key.
138
     * @return bool true if a value exists in cache, false if the value is not in the cache or expired.
139
     */
140 2
    public function exists($key)
141
    {
142 2
        $key = $this->buildKey($key);
143 2
        $value = $this->getValue($key);
144
145 2
        return $value !== false;
146
    }
147
148
    /**
149
     * Retrieves multiple values from cache with the specified keys.
150
     * Some caches (such as memcache, apc) allow retrieving multiple cached values at the same time,
151
     * which may improve the performance. In case a cache does not support this feature natively,
152
     * this method will try to simulate it.
153
     * @param string[] $keys list of string keys identifying the cached values
154
     * @return array list of cached values corresponding to the specified keys. The array
155
     * is returned in terms of (key, value) pairs.
156
     * If a value is not cached or expired, the corresponding array value will be false.
157
     * @since 2.0.7
158
     */
159 13
    public function multiGet($keys)
160
    {
161 13
        $keyMap = [];
162 13
        foreach ($keys as $key) {
163 13
            $keyMap[$key] = $this->buildKey($key);
164 13
        }
165 13
        $values = $this->getValues(array_values($keyMap));
166 13
        $results = [];
167 13
        foreach ($keyMap as $key => $newKey) {
168 13
            $results[$key] = false;
169 13
            if (isset($values[$newKey])) {
170 13
                if ($this->serializer === false) {
171
                    $results[$key] = $values[$newKey];
172
                } else {
173 13
                    $value = $this->serializer === null ? unserialize($values[$newKey])
174 13
                        : call_user_func($this->serializer[1], $values[$newKey]);
175
176 13
                    if (is_array($value) && !($value[1] instanceof Dependency && $value[1]->isChanged($this))) {
177 10
                        $results[$key] = $value[0];
178 10
                    }
179
                }
180 13
            }
181 13
        }
182
183 13
        return $results;
184
    }
185
186
    /**
187
     * Stores a value identified by a key into cache.
188
     * If the cache already contains such a key, the existing value and
189
     * expiration time will be replaced with the new ones, respectively.
190
     *
191
     * @param mixed $key a key identifying the value to be cached. This can be a simple string or
192
     * a complex data structure consisting of factors representing the key.
193
     * @param mixed $value the value to be cached
194
     * @param int $duration default duration in seconds before the cache will expire. If not set,
195
     * default [[ttl]] value is used.
196
     * @param Dependency $dependency dependency of the cached item. If the dependency changes,
197
     * the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
198
     * This parameter is ignored if [[serializer]] is false.
199
     * @return bool whether the value is successfully stored into cache
200
     */
201 73
    public function set($key, $value, $duration = null, $dependency = null)
202
    {
203 73
        if ($duration === null) {
204 56
            $duration = $this->defaultDuration;
205 56
        }
206
207 73
        if ($dependency !== null && $this->serializer !== false) {
208 8
            $dependency->evaluateDependency($this);
209 8
        }
210 73
        if ($this->serializer === null) {
211 73
            $value = serialize([$value, $dependency]);
212 73
        } elseif ($this->serializer !== false) {
213
            $value = call_user_func($this->serializer[0], [$value, $dependency]);
214
        }
215 73
        $key = $this->buildKey($key);
216
217 73
        return $this->setValue($key, $value, $duration);
218
    }
219
220
    /**
221
     * Stores multiple items in cache. Each item contains a value identified by a key.
222
     * If the cache already contains such a key, the existing value and
223
     * expiration time will be replaced with the new ones, respectively.
224
     *
225
     * @param array $items the items to be cached, as key-value pairs.
226
     * @param int $duration default number of seconds in which the cached values will expire. 0 means never expire.
227
     * @param Dependency $dependency dependency of the cached items. If the dependency changes,
228
     * the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
229
     * This parameter is ignored if [[serializer]] is false.
230
     * @return array array of failed keys
231
     * @since 2.0.7
232
     */
233 15
    public function multiSet($items, $duration = 0, $dependency = null)
234
    {
235 15
        if ($dependency !== null && $this->serializer !== false) {
236
            $dependency->evaluateDependency($this);
237
        }
238
239 15
        $data = [];
240 15
        foreach ($items as $key => $value) {
241 15
            if ($this->serializer === null) {
242 15
                $value = serialize([$value, $dependency]);
243 15
            } elseif ($this->serializer !== false) {
244
                $value = call_user_func($this->serializer[0], [$value, $dependency]);
245
            }
246
247 15
            $key = $this->buildKey($key);
248 15
            $data[$key] = $value;
249 15
        }
250
251 15
        return $this->setValues($data, $duration);
252
    }
253
254
    /**
255
     * Stores multiple items in cache. Each item contains a value identified by a key.
256
     * If the cache already contains such a key, the existing value and expiration time will be preserved.
257
     *
258
     * @param array $items the items to be cached, as key-value pairs.
259
     * @param int $duration default number of seconds in which the cached values will expire. 0 means never expire.
260
     * @param Dependency $dependency dependency of the cached items. If the dependency changes,
261
     * the corresponding values in the cache will be invalidated when it is fetched via [[get()]].
262
     * This parameter is ignored if [[serializer]] is false.
263
     * @return array array of failed keys
264
     * @since 2.0.7
265
     */
266 5
    public function multiAdd($items, $duration = 0, $dependency = null)
267
    {
268 5
        if ($dependency !== null && $this->serializer !== false) {
269
            $dependency->evaluateDependency($this);
270
        }
271
272 5
        $data = [];
273 5
        foreach ($items as $key => $value) {
274 5
            if ($this->serializer === null) {
275 5
                $value = serialize([$value, $dependency]);
276 5
            } elseif ($this->serializer !== false) {
277
                $value = call_user_func($this->serializer[0], [$value, $dependency]);
278
            }
279
280 5
            $key = $this->buildKey($key);
281 5
            $data[$key] = $value;
282 5
        }
283
284 5
        return $this->addValues($data, $duration);
285
    }
286
287
    /**
288
     * Stores a value identified by a key into cache if the cache does not contain this key.
289
     * Nothing will be done if the cache already contains the key.
290
     * @param mixed $key a key identifying the value to be cached. This can be a simple string or
291
     * a complex data structure consisting of factors representing the key.
292
     * @param mixed $value the value to be cached
293
     * @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
294
     * @param Dependency $dependency dependency of the cached item. If the dependency changes,
295
     * the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
296
     * This parameter is ignored if [[serializer]] is false.
297
     * @return bool whether the value is successfully stored into cache
298
     */
299 8
    public function add($key, $value, $duration = 0, $dependency = null)
300
    {
301 8
        if ($dependency !== null && $this->serializer !== false) {
302
            $dependency->evaluateDependency($this);
303
        }
304 8
        if ($this->serializer === null) {
305 8
            $value = serialize([$value, $dependency]);
306 8
        } elseif ($this->serializer !== false) {
307
            $value = call_user_func($this->serializer[0], [$value, $dependency]);
308
        }
309 8
        $key = $this->buildKey($key);
310
311 8
        return $this->addValue($key, $value, $duration);
312
    }
313
314
    /**
315
     * Deletes a value with the specified key from cache
316
     * @param mixed $key a key identifying the value to be deleted from cache. This can be a simple string or
317
     * a complex data structure consisting of factors representing the key.
318
     * @return bool if no error happens during deletion
319
     */
320 33
    public function delete($key)
321
    {
322 33
        $key = $this->buildKey($key);
323
324 33
        return $this->deleteValue($key);
325
    }
326
327
    /**
328
     * Deletes all values from cache.
329
     * Be careful of performing this operation if the cache is shared among multiple applications.
330
     * @return bool whether the flush operation was successful.
331
     */
332 48
    public function flush()
333
    {
334 48
        return $this->flushValues();
335
    }
336
337
    /**
338
     * Retrieves a value from cache with a specified key.
339
     * This method should be implemented by child classes to retrieve the data
340
     * from specific cache storage.
341
     * @param string $key a unique key identifying the cached value
342
     * @return mixed|false the value stored in cache, false if the value is not in the cache or expired. Most often
343
     * value is a string. If you have disabled [[serializer]], it could be something else.
344
     */
345
    abstract protected function getValue($key);
346
347
    /**
348
     * Stores a value identified by a key in cache.
349
     * This method should be implemented by child classes to store the data
350
     * in specific cache storage.
351
     * @param string $key the key identifying the value to be cached
352
     * @param mixed $value the value to be cached. Most often it's a string. If you have disabled [[serializer]],
353
     * it could be something else.
354
     * @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
355
     * @return bool true if the value is successfully stored into cache, false otherwise
356
     */
357
    abstract protected function setValue($key, $value, $duration);
358
359
    /**
360
     * Stores a value identified by a key into cache if the cache does not contain this key.
361
     * This method should be implemented by child classes to store the data
362
     * in specific cache storage.
363
     * @param string $key the key identifying the value to be cached
364
     * @param mixed $value the value to be cached. Most often it's a string. If you have disabled [[serializer]],
365
     * it could be something else.
366
     * @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
367
     * @return bool true if the value is successfully stored into cache, false otherwise
368
     */
369
    abstract protected function addValue($key, $value, $duration);
370
371
    /**
372
     * Deletes a value with the specified key from cache
373
     * This method should be implemented by child classes to delete the data from actual cache storage.
374
     * @param string $key the key of the value to be deleted
375
     * @return bool if no error happens during deletion
376
     */
377
    abstract protected function deleteValue($key);
378
379
    /**
380
     * Deletes all values from cache.
381
     * Child classes may implement this method to realize the flush operation.
382
     * @return bool whether the flush operation was successful.
383
     */
384
    abstract protected function flushValues();
385
386
    /**
387
     * Retrieves multiple values from cache with the specified keys.
388
     * The default implementation calls [[getValue()]] multiple times to retrieve
389
     * the cached values one by one. If the underlying cache storage supports multiget,
390
     * this method should be overridden to exploit that feature.
391
     * @param array $keys a list of keys identifying the cached values
392
     * @return array a list of cached values indexed by the keys
393
     */
394 10
    protected function getValues($keys)
395
    {
396 10
        $results = [];
397 10
        foreach ($keys as $key) {
398 10
            $results[$key] = $this->getValue($key);
399 10
        }
400
401 10
        return $results;
402
    }
403
404
    /**
405
     * Stores multiple key-value pairs in cache.
406
     * The default implementation calls [[setValue()]] multiple times store values one by one. If the underlying cache
407
     * storage supports multi-set, this method should be overridden to exploit that feature.
408
     * @param array $data array where key corresponds to cache key while value is the value stored
409
     * @param int $duration the number of seconds in which the cached values will expire. 0 means never expire.
410
     * @return array array of failed keys
411
     */
412 13
    protected function setValues($data, $duration)
413
    {
414 13
        $failedKeys = [];
415 13
        foreach ($data as $key => $value) {
416 13
            if ($this->setValue($key, $value, $duration) === false) {
417
                $failedKeys[] = $key;
418
            }
419 13
        }
420
421 13
        return $failedKeys;
422
    }
423
424
    /**
425
     * Adds multiple key-value pairs to cache.
426
     * The default implementation calls [[addValue()]] multiple times add values one by one. If the underlying cache
427
     * storage supports multi-add, this method should be overridden to exploit that feature.
428
     * @param array $data array where key corresponds to cache key while value is the value stored.
429
     * @param int $duration the number of seconds in which the cached values will expire. 0 means never expire.
430
     * @return array array of failed keys
431
     */
432 5
    protected function addValues($data, $duration)
433
    {
434 5
        $failedKeys = [];
435 5
        foreach ($data as $key => $value) {
436 5
            if ($this->addValue($key, $value, $duration) === false) {
437 5
                $failedKeys[] = $key;
438 5
            }
439 5
        }
440
441 5
        return $failedKeys;
442
    }
443
444
    /**
445
     * Returns whether there is a cache entry with a specified key.
446
     * This method is required by the interface [[\ArrayAccess]].
447
     * @param string $key a key identifying the cached value
448
     * @return bool
449
     */
450
    public function offsetExists($key)
451
    {
452
        return $this->get($key) !== false;
453
    }
454
455
    /**
456
     * Retrieves the value from cache with a specified key.
457
     * This method is required by the interface [[\ArrayAccess]].
458
     * @param string $key a key identifying the cached value
459
     * @return mixed the value stored in cache, false if the value is not in the cache or expired.
460
     */
461 5
    public function offsetGet($key)
462
    {
463 5
        return $this->get($key);
464
    }
465
466
    /**
467
     * Stores the value identified by a key into cache.
468
     * If the cache already contains such a key, the existing value will be
469
     * replaced with the new ones. To add expiration and dependencies, use the [[set()]] method.
470
     * This method is required by the interface [[\ArrayAccess]].
471
     * @param string $key the key identifying the value to be cached
472
     * @param mixed $value the value to be cached
473
     */
474 40
    public function offsetSet($key, $value)
475
    {
476 40
        $this->set($key, $value);
477 40
    }
478
479
    /**
480
     * Deletes the value with the specified key from cache
481
     * This method is required by the interface [[\ArrayAccess]].
482
     * @param string $key the key of the value to be deleted
483
     */
484
    public function offsetUnset($key)
485
    {
486
        $this->delete($key);
487
    }
488
}
489