AbstractAdapterTrait.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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 = strtr(substr_replace(base64_encode(pack('V', mt_rand())), static::NS_SEPARATOR, 5), '/', '_');
  116. try {
  117. $cleared = $this->doSave([static::NS_SEPARATOR.$this->namespace => $namespaceVersion], 0);
  118. } catch (\Exception $e) {
  119. $cleared = false;
  120. }
  121. if ($cleared = true === $cleared || [] === $cleared) {
  122. $this->namespaceVersion = $namespaceVersion;
  123. $this->ids = [];
  124. }
  125. } else {
  126. $namespaceToClear = $this->namespace.$prefix;
  127. }
  128. try {
  129. return $this->doClear($namespaceToClear) || $cleared;
  130. } catch (\Exception $e) {
  131. CacheItem::log($this->logger, 'Failed to clear the cache: '.$e->getMessage(), ['exception' => $e, 'cache-adapter' => get_debug_type($this)]);
  132. return false;
  133. }
  134. }
  135. /**
  136. * {@inheritdoc}
  137. *
  138. * @return bool
  139. */
  140. public function deleteItem($key)
  141. {
  142. return $this->deleteItems([$key]);
  143. }
  144. /**
  145. * {@inheritdoc}
  146. *
  147. * @return bool
  148. */
  149. public function deleteItems(array $keys)
  150. {
  151. $ids = [];
  152. foreach ($keys as $key) {
  153. $ids[$key] = $this->getId($key);
  154. unset($this->deferred[$key]);
  155. }
  156. try {
  157. if ($this->doDelete($ids)) {
  158. return true;
  159. }
  160. } catch (\Exception $e) {
  161. }
  162. $ok = true;
  163. // When bulk-delete failed, retry each item individually
  164. foreach ($ids as $key => $id) {
  165. try {
  166. $e = null;
  167. if ($this->doDelete([$id])) {
  168. continue;
  169. }
  170. } catch (\Exception $e) {
  171. }
  172. $message = 'Failed to delete key "{key}"'.($e instanceof \Exception ? ': '.$e->getMessage() : '.');
  173. CacheItem::log($this->logger, $message, ['key' => $key, 'exception' => $e, 'cache-adapter' => get_debug_type($this)]);
  174. $ok = false;
  175. }
  176. return $ok;
  177. }
  178. /**
  179. * {@inheritdoc}
  180. */
  181. public function getItem($key)
  182. {
  183. $id = $this->getId($key);
  184. if (isset($this->deferred[$key])) {
  185. $this->commit();
  186. }
  187. $isHit = false;
  188. $value = null;
  189. try {
  190. foreach ($this->doFetch([$id]) as $value) {
  191. $isHit = true;
  192. }
  193. return (self::$createCacheItem)($key, $value, $isHit);
  194. } catch (\Exception $e) {
  195. CacheItem::log($this->logger, 'Failed to fetch key "{key}": '.$e->getMessage(), ['key' => $key, 'exception' => $e, 'cache-adapter' => get_debug_type($this)]);
  196. }
  197. return (self::$createCacheItem)($key, null, false);
  198. }
  199. /**
  200. * {@inheritdoc}
  201. */
  202. public function getItems(array $keys = [])
  203. {
  204. $ids = [];
  205. $commit = false;
  206. foreach ($keys as $key) {
  207. $ids[] = $this->getId($key);
  208. $commit = $commit || isset($this->deferred[$key]);
  209. }
  210. if ($commit) {
  211. $this->commit();
  212. }
  213. try {
  214. $items = $this->doFetch($ids);
  215. } catch (\Exception $e) {
  216. CacheItem::log($this->logger, 'Failed to fetch items: '.$e->getMessage(), ['keys' => $keys, 'exception' => $e, 'cache-adapter' => get_debug_type($this)]);
  217. $items = [];
  218. }
  219. $ids = array_combine($ids, $keys);
  220. return $this->generateItems($items, $ids);
  221. }
  222. /**
  223. * {@inheritdoc}
  224. *
  225. * @return bool
  226. */
  227. public function save(CacheItemInterface $item)
  228. {
  229. if (!$item instanceof CacheItem) {
  230. return false;
  231. }
  232. $this->deferred[$item->getKey()] = $item;
  233. return $this->commit();
  234. }
  235. /**
  236. * {@inheritdoc}
  237. *
  238. * @return bool
  239. */
  240. public function saveDeferred(CacheItemInterface $item)
  241. {
  242. if (!$item instanceof CacheItem) {
  243. return false;
  244. }
  245. $this->deferred[$item->getKey()] = $item;
  246. return true;
  247. }
  248. /**
  249. * Enables/disables versioning of items.
  250. *
  251. * When versioning is enabled, clearing the cache is atomic and doesn't require listing existing keys to proceed,
  252. * but old keys may need garbage collection and extra round-trips to the back-end are required.
  253. *
  254. * Calling this method also clears the memoized namespace version and thus forces a resynchonization of it.
  255. *
  256. * @return bool the previous state of versioning
  257. */
  258. public function enableVersioning(bool $enable = true)
  259. {
  260. $wasEnabled = $this->versioningIsEnabled;
  261. $this->versioningIsEnabled = $enable;
  262. $this->namespaceVersion = '';
  263. $this->ids = [];
  264. return $wasEnabled;
  265. }
  266. /**
  267. * {@inheritdoc}
  268. */
  269. public function reset()
  270. {
  271. if ($this->deferred) {
  272. $this->commit();
  273. }
  274. $this->namespaceVersion = '';
  275. $this->ids = [];
  276. }
  277. /**
  278. * @return array
  279. */
  280. public function __sleep()
  281. {
  282. throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
  283. }
  284. public function __wakeup()
  285. {
  286. throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
  287. }
  288. public function __destruct()
  289. {
  290. if ($this->deferred) {
  291. $this->commit();
  292. }
  293. }
  294. private function generateItems(iterable $items, array &$keys): \Generator
  295. {
  296. $f = self::$createCacheItem;
  297. try {
  298. foreach ($items as $id => $value) {
  299. if (!isset($keys[$id])) {
  300. throw new InvalidArgumentException(sprintf('Could not match value id "%s" to keys "%s".', $id, implode('", "', $keys)));
  301. }
  302. $key = $keys[$id];
  303. unset($keys[$id]);
  304. yield $key => $f($key, $value, true);
  305. }
  306. } catch (\Exception $e) {
  307. CacheItem::log($this->logger, 'Failed to fetch items: '.$e->getMessage(), ['keys' => array_values($keys), 'exception' => $e, 'cache-adapter' => get_debug_type($this)]);
  308. }
  309. foreach ($keys as $key) {
  310. yield $key => $f($key, null, false);
  311. }
  312. }
  313. private function getId($key)
  314. {
  315. if ($this->versioningIsEnabled && '' === $this->namespaceVersion) {
  316. $this->ids = [];
  317. $this->namespaceVersion = '1'.static::NS_SEPARATOR;
  318. try {
  319. foreach ($this->doFetch([static::NS_SEPARATOR.$this->namespace]) as $v) {
  320. $this->namespaceVersion = $v;
  321. }
  322. if ('1'.static::NS_SEPARATOR === $this->namespaceVersion) {
  323. $this->namespaceVersion = strtr(substr_replace(base64_encode(pack('V', time())), static::NS_SEPARATOR, 5), '/', '_');
  324. $this->doSave([static::NS_SEPARATOR.$this->namespace => $this->namespaceVersion], 0);
  325. }
  326. } catch (\Exception $e) {
  327. }
  328. }
  329. if (\is_string($key) && isset($this->ids[$key])) {
  330. return $this->namespace.$this->namespaceVersion.$this->ids[$key];
  331. }
  332. \assert('' !== CacheItem::validateKey($key));
  333. $this->ids[$key] = $key;
  334. if (\count($this->ids) > 1000) {
  335. array_splice($this->ids, 0, 500); // stop memory leak if there are many keys
  336. }
  337. if (null === $this->maxIdLength) {
  338. return $this->namespace.$this->namespaceVersion.$key;
  339. }
  340. if (\strlen($id = $this->namespace.$this->namespaceVersion.$key) > $this->maxIdLength) {
  341. // Use MD5 to favor speed over security, which is not an issue here
  342. $this->ids[$key] = $id = substr_replace(base64_encode(hash('md5', $key, true)), static::NS_SEPARATOR, -(\strlen($this->namespaceVersion) + 2));
  343. $id = $this->namespace.$this->namespaceVersion.$id;
  344. }
  345. return $id;
  346. }
  347. /**
  348. * @internal
  349. */
  350. public static function handleUnserializeCallback(string $class)
  351. {
  352. throw new \DomainException('Class not found: '.$class);
  353. }
  354. }