AbstractAdapterTrait.php 11 KB

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