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

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