4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Cache\Traits;
14 use Psr\Log\LoggerAwareTrait;
15 use Symfony\Component\Cache\CacheItem;
18 * @author Nicolas Grekas <p@tchwork.com>
27 private $namespaceVersion = '';
28 private $versioningIsEnabled = false;
29 private $deferred = [];
32 * @var int|null The maximum length to enforce for identifiers or null when no limit applies
34 protected $maxIdLength;
37 * Fetches several cache items.
39 * @param array $ids The cache identifiers to fetch
41 * @return array|\Traversable The corresponding values found in the cache
43 abstract protected function doFetch(array $ids);
46 * Confirms if the cache contains specified cache item.
48 * @param string $id The identifier for which to check existence
50 * @return bool True if item exists in the cache, false otherwise
52 abstract protected function doHave($id);
55 * Deletes all items in the pool.
57 * @param string $namespace The prefix used for all identifiers managed by this pool
59 * @return bool True if the pool was successfully cleared, false otherwise
61 abstract protected function doClear($namespace);
64 * Removes multiple items from the pool.
66 * @param array $ids An array of identifiers that should be removed from the pool
68 * @return bool True if the items were successfully removed, false otherwise
70 abstract protected function doDelete(array $ids);
73 * Persists several cache items immediately.
75 * @param array $values The values to cache, indexed by their cache identifier
76 * @param int $lifetime The lifetime of the cached values, 0 for persisting until manual cleaning
78 * @return array|bool The identifiers that failed to be cached or a boolean stating if caching succeeded or not
80 abstract protected function doSave(array $values, $lifetime);
85 public function hasItem($key)
87 $id = $this->getId($key);
89 if (isset($this->deferred[$key])) {
94 return $this->doHave($id);
95 } catch (\Exception $e) {
96 CacheItem::log($this->logger, 'Failed to check if key "{key}" is cached', ['key' => $key, 'exception' => $e]);
105 public function clear()
107 $this->deferred = [];
108 if ($cleared = $this->versioningIsEnabled) {
109 $namespaceVersion = substr_replace(base64_encode(pack('V', mt_rand())), static::NS_SEPARATOR, 5);
111 $cleared = $this->doSave([static::NS_SEPARATOR.$this->namespace => $namespaceVersion], 0);
112 } catch (\Exception $e) {
115 if ($cleared = true === $cleared || [] === $cleared) {
116 $this->namespaceVersion = $namespaceVersion;
121 return $this->doClear($this->namespace) || $cleared;
122 } catch (\Exception $e) {
123 CacheItem::log($this->logger, 'Failed to clear the cache', ['exception' => $e]);
132 public function deleteItem($key)
134 return $this->deleteItems([$key]);
140 public function deleteItems(array $keys)
144 foreach ($keys as $key) {
145 $ids[$key] = $this->getId($key);
146 unset($this->deferred[$key]);
150 if ($this->doDelete($ids)) {
153 } catch (\Exception $e) {
158 // When bulk-delete failed, retry each item individually
159 foreach ($ids as $key => $id) {
162 if ($this->doDelete([$id])) {
165 } catch (\Exception $e) {
167 CacheItem::log($this->logger, 'Failed to delete key "{key}"', ['key' => $key, 'exception' => $e]);
175 * Enables/disables versioning of items.
177 * When versioning is enabled, clearing the cache is atomic and doesn't require listing existing keys to proceed,
178 * but old keys may need garbage collection and extra round-trips to the back-end are required.
180 * Calling this method also clears the memoized namespace version and thus forces a resynchonization of it.
182 * @param bool $enable
184 * @return bool the previous state of versioning
186 public function enableVersioning($enable = true)
188 $wasEnabled = $this->versioningIsEnabled;
189 $this->versioningIsEnabled = (bool) $enable;
190 $this->namespaceVersion = '';
198 public function reset()
200 if ($this->deferred) {
203 $this->namespaceVersion = '';
207 * Like the native unserialize() function but throws an exception if anything goes wrong.
209 * @param string $value
215 protected static function unserialize($value)
217 if ('b:0;' === $value) {
220 $unserializeCallbackHandler = ini_set('unserialize_callback_func', __CLASS__.'::handleUnserializeCallback');
222 if (false !== $value = unserialize($value)) {
225 throw new \DomainException('Failed to unserialize cached value.');
226 } catch (\Error $e) {
227 throw new \ErrorException($e->getMessage(), $e->getCode(), \E_ERROR, $e->getFile(), $e->getLine());
229 ini_set('unserialize_callback_func', $unserializeCallbackHandler);
233 private function getId($key)
235 CacheItem::validateKey($key);
237 if ($this->versioningIsEnabled && '' === $this->namespaceVersion) {
238 $this->namespaceVersion = '1'.static::NS_SEPARATOR;
240 foreach ($this->doFetch([static::NS_SEPARATOR.$this->namespace]) as $v) {
241 $this->namespaceVersion = $v;
243 if ('1'.static::NS_SEPARATOR === $this->namespaceVersion) {
244 $this->namespaceVersion = substr_replace(base64_encode(pack('V', time())), static::NS_SEPARATOR, 5);
245 $this->doSave([static::NS_SEPARATOR.$this->namespace => $this->namespaceVersion], 0);
247 } catch (\Exception $e) {
251 if (null === $this->maxIdLength) {
252 return $this->namespace.$this->namespaceVersion.$key;
254 if (\strlen($id = $this->namespace.$this->namespaceVersion.$key) > $this->maxIdLength) {
255 $id = $this->namespace.$this->namespaceVersion.substr_replace(base64_encode(hash('sha256', $key, true)), static::NS_SEPARATOR, -(\strlen($this->namespaceVersion) + 22));
264 public static function handleUnserializeCallback($class)
266 throw new \DomainException('Class not found: '.$class);