vendor/symfony/cache/Traits/AbstractAdapterTrait.php line 195

  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Component\Cache\Traits;
  11. use Psr\Cache\CacheItemInterface;
  12. use Psr\Log\LoggerAwareTrait;
  13. use Symfony\Component\Cache\CacheItem;
  14. use Symfony\Component\Cache\Exception\InvalidArgumentException;
  15. /**
  16.  * @author Nicolas Grekas <p@tchwork.com>
  17.  *
  18.  * @internal
  19.  */
  20. trait AbstractAdapterTrait
  21. {
  22.     use LoggerAwareTrait;
  23.     /**
  24.      * needs to be set by class, signature is function(string <key>, mixed <value>, bool <isHit>).
  25.      */
  26.     private static \Closure $createCacheItem;
  27.     /**
  28.      * needs to be set by class, signature is function(array <deferred>, string <namespace>, array <&expiredIds>).
  29.      */
  30.     private static \Closure $mergeByLifetime;
  31.     private string $namespace '';
  32.     private int $defaultLifetime;
  33.     private string $namespaceVersion '';
  34.     private bool $versioningIsEnabled false;
  35.     private array $deferred = [];
  36.     private array $ids = [];
  37.     /**
  38.      * @var int|null The maximum length to enforce for identifiers or null when no limit applies
  39.      */
  40.     protected $maxIdLength;
  41.     /**
  42.      * Fetches several cache items.
  43.      *
  44.      * @param array $ids The cache identifiers to fetch
  45.      *
  46.      * @return array|\Traversable
  47.      */
  48.     abstract protected function doFetch(array $ids): iterable;
  49.     /**
  50.      * Confirms if the cache contains specified cache item.
  51.      *
  52.      * @param string $id The identifier for which to check existence
  53.      */
  54.     abstract protected function doHave(string $id): bool;
  55.     /**
  56.      * Deletes all items in the pool.
  57.      *
  58.      * @param string $namespace The prefix used for all identifiers managed by this pool
  59.      */
  60.     abstract protected function doClear(string $namespace): bool;
  61.     /**
  62.      * Removes multiple items from the pool.
  63.      *
  64.      * @param array $ids An array of identifiers that should be removed from the pool
  65.      */
  66.     abstract protected function doDelete(array $ids): bool;
  67.     /**
  68.      * Persists several cache items immediately.
  69.      *
  70.      * @param array $values   The values to cache, indexed by their cache identifier
  71.      * @param int   $lifetime The lifetime of the cached values, 0 for persisting until manual cleaning
  72.      *
  73.      * @return array|bool The identifiers that failed to be cached or a boolean stating if caching succeeded or not
  74.      */
  75.     abstract protected function doSave(array $valuesint $lifetime): array|bool;
  76.     public function hasItem(mixed $key): bool
  77.     {
  78.         $id $this->getId($key);
  79.         if (isset($this->deferred[$key])) {
  80.             $this->commit();
  81.         }
  82.         try {
  83.             return $this->doHave($id);
  84.         } catch (\Exception $e) {
  85.             CacheItem::log($this->logger'Failed to check if key "{key}" is cached: '.$e->getMessage(), ['key' => $key'exception' => $e'cache-adapter' => get_debug_type($this)]);
  86.             return false;
  87.         }
  88.     }
  89.     public function clear(string $prefix ''): bool
  90.     {
  91.         $this->deferred = [];
  92.         if ($cleared $this->versioningIsEnabled) {
  93.             if ('' === $namespaceVersionToClear $this->namespaceVersion) {
  94.                 foreach ($this->doFetch([static::NS_SEPARATOR.$this->namespace]) as $v) {
  95.                     $namespaceVersionToClear $v;
  96.                 }
  97.             }
  98.             $namespaceToClear $this->namespace.$namespaceVersionToClear;
  99.             $namespaceVersion self::formatNamespaceVersion(mt_rand());
  100.             try {
  101.                 $e $this->doSave([static::NS_SEPARATOR.$this->namespace => $namespaceVersion], 0);
  102.             } catch (\Exception $e) {
  103.             }
  104.             if (true !== $e && [] !== $e) {
  105.                 $cleared false;
  106.                 $message 'Failed to save the new namespace'.($e instanceof \Exception ': '.$e->getMessage() : '.');
  107.                 CacheItem::log($this->logger$message, ['exception' => $e instanceof \Exception $e null'cache-adapter' => get_debug_type($this)]);
  108.             } else {
  109.                 $this->namespaceVersion $namespaceVersion;
  110.                 $this->ids = [];
  111.             }
  112.         } else {
  113.             $namespaceToClear $this->namespace.$prefix;
  114.         }
  115.         try {
  116.             return $this->doClear($namespaceToClear) || $cleared;
  117.         } catch (\Exception $e) {
  118.             CacheItem::log($this->logger'Failed to clear the cache: '.$e->getMessage(), ['exception' => $e'cache-adapter' => get_debug_type($this)]);
  119.             return false;
  120.         }
  121.     }
  122.     public function deleteItem(mixed $key): bool
  123.     {
  124.         return $this->deleteItems([$key]);
  125.     }
  126.     public function deleteItems(array $keys): bool
  127.     {
  128.         $ids = [];
  129.         foreach ($keys as $key) {
  130.             $ids[$key] = $this->getId($key);
  131.             unset($this->deferred[$key]);
  132.         }
  133.         try {
  134.             if ($this->doDelete($ids)) {
  135.                 return true;
  136.             }
  137.         } catch (\Exception) {
  138.         }
  139.         $ok true;
  140.         // When bulk-delete failed, retry each item individually
  141.         foreach ($ids as $key => $id) {
  142.             try {
  143.                 $e null;
  144.                 if ($this->doDelete([$id])) {
  145.                     continue;
  146.                 }
  147.             } catch (\Exception $e) {
  148.             }
  149.             $message 'Failed to delete key "{key}"'.($e instanceof \Exception ': '.$e->getMessage() : '.');
  150.             CacheItem::log($this->logger$message, ['key' => $key'exception' => $e'cache-adapter' => get_debug_type($this)]);
  151.             $ok false;
  152.         }
  153.         return $ok;
  154.     }
  155.     public function getItem(mixed $key): CacheItem
  156.     {
  157.         $id $this->getId($key);
  158.         if (isset($this->deferred[$key])) {
  159.             $this->commit();
  160.         }
  161.         $isHit false;
  162.         $value null;
  163.         try {
  164.             foreach ($this->doFetch([$id]) as $value) {
  165.                 $isHit true;
  166.             }
  167.             return (self::$createCacheItem)($key$value$isHit);
  168.         } catch (\Exception $e) {
  169.             CacheItem::log($this->logger'Failed to fetch key "{key}": '.$e->getMessage(), ['key' => $key'exception' => $e'cache-adapter' => get_debug_type($this)]);
  170.         }
  171.         return (self::$createCacheItem)($keynullfalse);
  172.     }
  173.     public function getItems(array $keys = []): iterable
  174.     {
  175.         $ids = [];
  176.         $commit false;
  177.         foreach ($keys as $key) {
  178.             $ids[] = $this->getId($key);
  179.             $commit $commit || isset($this->deferred[$key]);
  180.         }
  181.         if ($commit) {
  182.             $this->commit();
  183.         }
  184.         try {
  185.             $items $this->doFetch($ids);
  186.         } catch (\Exception $e) {
  187.             CacheItem::log($this->logger'Failed to fetch items: '.$e->getMessage(), ['keys' => $keys'exception' => $e'cache-adapter' => get_debug_type($this)]);
  188.             $items = [];
  189.         }
  190.         $ids array_combine($ids$keys);
  191.         return $this->generateItems($items$ids);
  192.     }
  193.     public function save(CacheItemInterface $item): bool
  194.     {
  195.         if (!$item instanceof CacheItem) {
  196.             return false;
  197.         }
  198.         $this->deferred[$item->getKey()] = $item;
  199.         return $this->commit();
  200.     }
  201.     public function saveDeferred(CacheItemInterface $item): bool
  202.     {
  203.         if (!$item instanceof CacheItem) {
  204.             return false;
  205.         }
  206.         $this->deferred[$item->getKey()] = $item;
  207.         return true;
  208.     }
  209.     /**
  210.      * Enables/disables versioning of items.
  211.      *
  212.      * When versioning is enabled, clearing the cache is atomic and doesn't require listing existing keys to proceed,
  213.      * but old keys may need garbage collection and extra round-trips to the back-end are required.
  214.      *
  215.      * Calling this method also clears the memoized namespace version and thus forces a resynchronization of it.
  216.      *
  217.      * @return bool the previous state of versioning
  218.      */
  219.     public function enableVersioning(bool $enable true): bool
  220.     {
  221.         $wasEnabled $this->versioningIsEnabled;
  222.         $this->versioningIsEnabled $enable;
  223.         $this->namespaceVersion '';
  224.         $this->ids = [];
  225.         return $wasEnabled;
  226.     }
  227.     public function reset()
  228.     {
  229.         if ($this->deferred) {
  230.             $this->commit();
  231.         }
  232.         $this->namespaceVersion '';
  233.         $this->ids = [];
  234.     }
  235.     public function __sleep(): array
  236.     {
  237.         throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
  238.     }
  239.     public function __wakeup()
  240.     {
  241.         throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
  242.     }
  243.     public function __destruct()
  244.     {
  245.         if ($this->deferred) {
  246.             $this->commit();
  247.         }
  248.     }
  249.     private function generateItems(iterable $items, array &$keys): \Generator
  250.     {
  251.         $f self::$createCacheItem;
  252.         try {
  253.             foreach ($items as $id => $value) {
  254.                 if (!isset($keys[$id])) {
  255.                     throw new InvalidArgumentException(sprintf('Could not match value id "%s" to keys "%s".'$idimplode('", "'$keys)));
  256.                 }
  257.                 $key $keys[$id];
  258.                 unset($keys[$id]);
  259.                 yield $key => $f($key$valuetrue);
  260.             }
  261.         } catch (\Exception $e) {
  262.             CacheItem::log($this->logger'Failed to fetch items: '.$e->getMessage(), ['keys' => array_values($keys), 'exception' => $e'cache-adapter' => get_debug_type($this)]);
  263.         }
  264.         foreach ($keys as $key) {
  265.             yield $key => $f($keynullfalse);
  266.         }
  267.     }
  268.     /**
  269.      * @internal
  270.      */
  271.     protected function getId(mixed $key)
  272.     {
  273.         if ($this->versioningIsEnabled && '' === $this->namespaceVersion) {
  274.             $this->ids = [];
  275.             $this->namespaceVersion '1'.static::NS_SEPARATOR;
  276.             try {
  277.                 foreach ($this->doFetch([static::NS_SEPARATOR.$this->namespace]) as $v) {
  278.                     $this->namespaceVersion $v;
  279.                 }
  280.                 $e true;
  281.                 if ('1'.static::NS_SEPARATOR === $this->namespaceVersion) {
  282.                     $this->namespaceVersion self::formatNamespaceVersion(time());
  283.                     $e $this->doSave([static::NS_SEPARATOR.$this->namespace => $this->namespaceVersion], 0);
  284.                 }
  285.             } catch (\Exception $e) {
  286.             }
  287.             if (true !== $e && [] !== $e) {
  288.                 $message 'Failed to save the new namespace'.($e instanceof \Exception ': '.$e->getMessage() : '.');
  289.                 CacheItem::log($this->logger$message, ['exception' => $e instanceof \Exception $e null'cache-adapter' => get_debug_type($this)]);
  290.             }
  291.         }
  292.         if (\is_string($key) && isset($this->ids[$key])) {
  293.             return $this->namespace.$this->namespaceVersion.$this->ids[$key];
  294.         }
  295.         \assert('' !== CacheItem::validateKey($key));
  296.         $this->ids[$key] = $key;
  297.         if (\count($this->ids) > 1000) {
  298.             $this->ids \array_slice($this->ids500nulltrue); // stop memory leak if there are many keys
  299.         }
  300.         if (null === $this->maxIdLength) {
  301.             return $this->namespace.$this->namespaceVersion.$key;
  302.         }
  303.         if (\strlen($id $this->namespace.$this->namespaceVersion.$key) > $this->maxIdLength) {
  304.             // Use MD5 to favor speed over security, which is not an issue here
  305.             $this->ids[$key] = $id substr_replace(base64_encode(hash('md5'$keytrue)), static::NS_SEPARATOR, -(\strlen($this->namespaceVersion) + 2));
  306.             $id $this->namespace.$this->namespaceVersion.$id;
  307.         }
  308.         return $id;
  309.     }
  310.     /**
  311.      * @internal
  312.      */
  313.     public static function handleUnserializeCallback(string $class)
  314.     {
  315.         throw new \DomainException('Class not found: '.$class);
  316.     }
  317.     private static function formatNamespaceVersion(int $value): string
  318.     {
  319.         return strtr(substr_replace(base64_encode(pack('V'$value)), static::NS_SEPARATOR5), '/''_');
  320.     }
  321. }