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

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