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 = [];
33 * @var int|null The maximum length to enforce for identifiers or null when no limit applies
35 protected $maxIdLength;
38 * Fetches several cache items.
40 * @param array $ids The cache identifiers to fetch
42 * @return array|\Traversable The corresponding values found in the cache
44 abstract protected function doFetch(array $ids);
47 * Confirms if the cache contains specified cache item.
49 * @param string $id The identifier for which to check existence
51 * @return bool True if item exists in the cache, false otherwise
53 abstract protected function doHave($id);
56 * Deletes all items in the pool.
58 * @param string $namespace The prefix used for all identifiers managed by this pool
60 * @return bool True if the pool was successfully cleared, false otherwise
62 abstract protected function doClear($namespace);
65 * Removes multiple items from the pool.
67 * @param array $ids An array of identifiers that should be removed from the pool
69 * @return bool True if the items were successfully removed, false otherwise
71 abstract protected function doDelete(array $ids);
74 * Persists several cache items immediately.
76 * @param array $values The values to cache, indexed by their cache identifier
77 * @param int $lifetime The lifetime of the cached values, 0 for persisting until manual cleaning
79 * @return array|bool The identifiers that failed to be cached or a boolean stating if caching succeeded or not
81 abstract protected function doSave(array $values, int $lifetime);
88 public function hasItem($key)
90 $id = $this->getId($key);
92 if (isset($this->deferred[$key])) {
97 return $this->doHave($id);
98 } catch (\Exception $e) {
99 CacheItem::log($this->logger, 'Failed to check if key "{key}" is cached: '.$e->getMessage(), ['key' => $key, 'exception' => $e]);
108 * @param string $prefix
112 public function clear(/* string $prefix = '' */)
114 $this->deferred = [];
115 if ($cleared = $this->versioningIsEnabled) {
116 if ('' === $namespaceVersionToClear = $this->namespaceVersion) {
117 foreach ($this->doFetch([static::NS_SEPARATOR.$this->namespace]) as $v) {
118 $namespaceVersionToClear = $v;
121 $namespaceToClear = $this->namespace.$namespaceVersionToClear;
122 $namespaceVersion = self::formatNamespaceVersion(mt_rand());
124 $e = $this->doSave([static::NS_SEPARATOR.$this->namespace => $namespaceVersion], 0);
125 } catch (\Exception $e) {
127 if (true !== $e && [] !== $e) {
129 $message = 'Failed to save the new namespace'.($e instanceof \Exception ? ': '.$e->getMessage() : '.');
130 CacheItem::log($this->logger, $message, ['exception' => $e instanceof \Exception ? $e : null]);
132 $this->namespaceVersion = $namespaceVersion;
136 $prefix = 0 < \func_num_args() ? (string) func_get_arg(0) : '';
137 $namespaceToClear = $this->namespace.$prefix;
141 return $this->doClear($namespaceToClear) || $cleared;
142 } catch (\Exception $e) {
143 CacheItem::log($this->logger, 'Failed to clear the cache: '.$e->getMessage(), ['exception' => $e]);
154 public function deleteItem($key)
156 return $this->deleteItems([$key]);
164 public function deleteItems(array $keys)
168 foreach ($keys as $key) {
169 $ids[$key] = $this->getId($key);
170 unset($this->deferred[$key]);
174 if ($this->doDelete($ids)) {
177 } catch (\Exception $e) {
182 // When bulk-delete failed, retry each item individually
183 foreach ($ids as $key => $id) {
186 if ($this->doDelete([$id])) {
189 } catch (\Exception $e) {
191 $message = 'Failed to delete key "{key}"'.($e instanceof \Exception ? ': '.$e->getMessage() : '.');
192 CacheItem::log($this->logger, $message, ['key' => $key, 'exception' => $e]);
200 * Enables/disables versioning of items.
202 * When versioning is enabled, clearing the cache is atomic and doesn't require listing existing keys to proceed,
203 * but old keys may need garbage collection and extra round-trips to the back-end are required.
205 * Calling this method also clears the memoized namespace version and thus forces a resynchonization of it.
207 * @param bool $enable
209 * @return bool the previous state of versioning
211 public function enableVersioning($enable = true)
213 $wasEnabled = $this->versioningIsEnabled;
214 $this->versioningIsEnabled = (bool) $enable;
215 $this->namespaceVersion = '';
224 public function reset()
226 if ($this->deferred) {
229 $this->namespaceVersion = '';
234 * Like the native unserialize() function but throws an exception if anything goes wrong.
236 * @param string $value
242 * @deprecated since Symfony 4.2, use DefaultMarshaller instead.
244 protected static function unserialize($value)
246 @trigger_error(sprintf('The "%s::unserialize()" method is deprecated since Symfony 4.2, use DefaultMarshaller instead.', __CLASS__), \E_USER_DEPRECATED);
248 if ('b:0;' === $value) {
251 $unserializeCallbackHandler = ini_set('unserialize_callback_func', __CLASS__.'::handleUnserializeCallback');
253 if (false !== $value = unserialize($value)) {
256 throw new \DomainException('Failed to unserialize cached value.');
257 } catch (\Error $e) {
258 throw new \ErrorException($e->getMessage(), $e->getCode(), \E_ERROR, $e->getFile(), $e->getLine());
260 ini_set('unserialize_callback_func', $unserializeCallbackHandler);
264 private function getId($key): string
266 if ($this->versioningIsEnabled && '' === $this->namespaceVersion) {
268 $this->namespaceVersion = '1'.static::NS_SEPARATOR;
270 foreach ($this->doFetch([static::NS_SEPARATOR.$this->namespace]) as $v) {
271 $this->namespaceVersion = $v;
274 if ('1'.static::NS_SEPARATOR === $this->namespaceVersion) {
275 $this->namespaceVersion = self::formatNamespaceVersion(time());
276 $e = $this->doSave([static::NS_SEPARATOR.$this->namespace => $this->namespaceVersion], 0);
278 } catch (\Exception $e) {
280 if (true !== $e && [] !== $e) {
281 $message = 'Failed to save the new namespace'.($e instanceof \Exception ? ': '.$e->getMessage() : '.');
282 CacheItem::log($this->logger, $message, ['exception' => $e instanceof \Exception ? $e : null]);
286 if (\is_string($key) && isset($this->ids[$key])) {
287 return $this->namespace.$this->namespaceVersion.$this->ids[$key];
289 CacheItem::validateKey($key);
290 $this->ids[$key] = $key;
292 if (\count($this->ids) > 1000) {
293 $this->ids = \array_slice($this->ids, 500, null, true); // stop memory leak if there are many keys
296 if (null === $this->maxIdLength) {
297 return $this->namespace.$this->namespaceVersion.$key;
299 if (\strlen($id = $this->namespace.$this->namespaceVersion.$key) > $this->maxIdLength) {
300 // Use MD5 to favor speed over security, which is not an issue here
301 $this->ids[$key] = $id = substr_replace(base64_encode(hash('md5', $key, true)), static::NS_SEPARATOR, -(\strlen($this->namespaceVersion) + 2));
302 $id = $this->namespace.$this->namespaceVersion.$id;
311 public static function handleUnserializeCallback($class)
313 throw new \DomainException('Class not found: '.$class);
316 private static function formatNamespaceVersion(int $value): string
318 return strtr(substr_replace(base64_encode(pack('V', $value)), static::NS_SEPARATOR, 5), '/', '_');