ChainAdapter.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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\Adapter;
  11. use Psr\Cache\CacheItemInterface;
  12. use Psr\Cache\CacheItemPoolInterface;
  13. use Symfony\Component\Cache\CacheItem;
  14. use Symfony\Component\Cache\Exception\InvalidArgumentException;
  15. use Symfony\Component\Cache\PruneableInterface;
  16. use Symfony\Component\Cache\ResettableInterface;
  17. use Symfony\Component\Cache\Traits\ContractsTrait;
  18. use Symfony\Contracts\Cache\CacheInterface;
  19. use Symfony\Contracts\Service\ResetInterface;
  20. /**
  21. * Chains several adapters together.
  22. *
  23. * Cached items are fetched from the first adapter having them in its data store.
  24. * They are saved and deleted in all adapters at once.
  25. *
  26. * @author Kévin Dunglas <dunglas@gmail.com>
  27. */
  28. class ChainAdapter implements AdapterInterface, CacheInterface, PruneableInterface, ResettableInterface
  29. {
  30. use ContractsTrait;
  31. private $adapters = [];
  32. private $adapterCount;
  33. private $syncItem;
  34. /**
  35. * @param CacheItemPoolInterface[] $adapters The ordered list of adapters used to fetch cached items
  36. * @param int $defaultLifetime The default lifetime of items propagated from lower adapters to upper ones
  37. */
  38. public function __construct(array $adapters, int $defaultLifetime = 0)
  39. {
  40. if (!$adapters) {
  41. throw new InvalidArgumentException('At least one adapter must be specified.');
  42. }
  43. foreach ($adapters as $adapter) {
  44. if (!$adapter instanceof CacheItemPoolInterface) {
  45. throw new InvalidArgumentException(sprintf('The class "%s" does not implement the "%s" interface.', get_debug_type($adapter), CacheItemPoolInterface::class));
  46. }
  47. if (\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) && $adapter instanceof ApcuAdapter && !filter_var(ini_get('apc.enable_cli'), \FILTER_VALIDATE_BOOLEAN)) {
  48. continue; // skip putting APCu in the chain when the backend is disabled
  49. }
  50. if ($adapter instanceof AdapterInterface) {
  51. $this->adapters[] = $adapter;
  52. } else {
  53. $this->adapters[] = new ProxyAdapter($adapter);
  54. }
  55. }
  56. $this->adapterCount = \count($this->adapters);
  57. $this->syncItem = \Closure::bind(
  58. static function ($sourceItem, $item, $sourceMetadata = null) use ($defaultLifetime) {
  59. $sourceItem->isTaggable = false;
  60. $sourceMetadata = $sourceMetadata ?? $sourceItem->metadata;
  61. unset($sourceMetadata[CacheItem::METADATA_TAGS]);
  62. $item->value = $sourceItem->value;
  63. $item->isHit = $sourceItem->isHit;
  64. $item->metadata = $item->newMetadata = $sourceItem->metadata = $sourceMetadata;
  65. if (isset($item->metadata[CacheItem::METADATA_EXPIRY])) {
  66. $item->expiresAt(\DateTime::createFromFormat('U.u', sprintf('%.6F', $item->metadata[CacheItem::METADATA_EXPIRY])));
  67. } elseif (0 < $defaultLifetime) {
  68. $item->expiresAfter($defaultLifetime);
  69. }
  70. return $item;
  71. },
  72. null,
  73. CacheItem::class
  74. );
  75. }
  76. /**
  77. * {@inheritdoc}
  78. */
  79. public function get(string $key, callable $callback, float $beta = null, array &$metadata = null)
  80. {
  81. $lastItem = null;
  82. $i = 0;
  83. $wrap = function (CacheItem $item = null) use ($key, $callback, $beta, &$wrap, &$i, &$lastItem, &$metadata) {
  84. $adapter = $this->adapters[$i];
  85. if (isset($this->adapters[++$i])) {
  86. $callback = $wrap;
  87. $beta = \INF === $beta ? \INF : 0;
  88. }
  89. if ($adapter instanceof CacheInterface) {
  90. $value = $adapter->get($key, $callback, $beta, $metadata);
  91. } else {
  92. $value = $this->doGet($adapter, $key, $callback, $beta, $metadata);
  93. }
  94. if (null !== $item) {
  95. ($this->syncItem)($lastItem = $lastItem ?? $item, $item, $metadata);
  96. }
  97. return $value;
  98. };
  99. return $wrap();
  100. }
  101. /**
  102. * {@inheritdoc}
  103. */
  104. public function getItem($key)
  105. {
  106. $syncItem = $this->syncItem;
  107. $misses = [];
  108. foreach ($this->adapters as $i => $adapter) {
  109. $item = $adapter->getItem($key);
  110. if ($item->isHit()) {
  111. while (0 <= --$i) {
  112. $this->adapters[$i]->save($syncItem($item, $misses[$i]));
  113. }
  114. return $item;
  115. }
  116. $misses[$i] = $item;
  117. }
  118. return $item;
  119. }
  120. /**
  121. * {@inheritdoc}
  122. */
  123. public function getItems(array $keys = [])
  124. {
  125. return $this->generateItems($this->adapters[0]->getItems($keys), 0);
  126. }
  127. private function generateItems(iterable $items, int $adapterIndex)
  128. {
  129. $missing = [];
  130. $misses = [];
  131. $nextAdapterIndex = $adapterIndex + 1;
  132. $nextAdapter = $this->adapters[$nextAdapterIndex] ?? null;
  133. foreach ($items as $k => $item) {
  134. if (!$nextAdapter || $item->isHit()) {
  135. yield $k => $item;
  136. } else {
  137. $missing[] = $k;
  138. $misses[$k] = $item;
  139. }
  140. }
  141. if ($missing) {
  142. $syncItem = $this->syncItem;
  143. $adapter = $this->adapters[$adapterIndex];
  144. $items = $this->generateItems($nextAdapter->getItems($missing), $nextAdapterIndex);
  145. foreach ($items as $k => $item) {
  146. if ($item->isHit()) {
  147. $adapter->save($syncItem($item, $misses[$k]));
  148. }
  149. yield $k => $item;
  150. }
  151. }
  152. }
  153. /**
  154. * {@inheritdoc}
  155. *
  156. * @return bool
  157. */
  158. public function hasItem($key)
  159. {
  160. foreach ($this->adapters as $adapter) {
  161. if ($adapter->hasItem($key)) {
  162. return true;
  163. }
  164. }
  165. return false;
  166. }
  167. /**
  168. * {@inheritdoc}
  169. *
  170. * @return bool
  171. */
  172. public function clear(string $prefix = '')
  173. {
  174. $cleared = true;
  175. $i = $this->adapterCount;
  176. while ($i--) {
  177. if ($this->adapters[$i] instanceof AdapterInterface) {
  178. $cleared = $this->adapters[$i]->clear($prefix) && $cleared;
  179. } else {
  180. $cleared = $this->adapters[$i]->clear() && $cleared;
  181. }
  182. }
  183. return $cleared;
  184. }
  185. /**
  186. * {@inheritdoc}
  187. *
  188. * @return bool
  189. */
  190. public function deleteItem($key)
  191. {
  192. $deleted = true;
  193. $i = $this->adapterCount;
  194. while ($i--) {
  195. $deleted = $this->adapters[$i]->deleteItem($key) && $deleted;
  196. }
  197. return $deleted;
  198. }
  199. /**
  200. * {@inheritdoc}
  201. *
  202. * @return bool
  203. */
  204. public function deleteItems(array $keys)
  205. {
  206. $deleted = true;
  207. $i = $this->adapterCount;
  208. while ($i--) {
  209. $deleted = $this->adapters[$i]->deleteItems($keys) && $deleted;
  210. }
  211. return $deleted;
  212. }
  213. /**
  214. * {@inheritdoc}
  215. *
  216. * @return bool
  217. */
  218. public function save(CacheItemInterface $item)
  219. {
  220. $saved = true;
  221. $i = $this->adapterCount;
  222. while ($i--) {
  223. $saved = $this->adapters[$i]->save($item) && $saved;
  224. }
  225. return $saved;
  226. }
  227. /**
  228. * {@inheritdoc}
  229. *
  230. * @return bool
  231. */
  232. public function saveDeferred(CacheItemInterface $item)
  233. {
  234. $saved = true;
  235. $i = $this->adapterCount;
  236. while ($i--) {
  237. $saved = $this->adapters[$i]->saveDeferred($item) && $saved;
  238. }
  239. return $saved;
  240. }
  241. /**
  242. * {@inheritdoc}
  243. *
  244. * @return bool
  245. */
  246. public function commit()
  247. {
  248. $committed = true;
  249. $i = $this->adapterCount;
  250. while ($i--) {
  251. $committed = $this->adapters[$i]->commit() && $committed;
  252. }
  253. return $committed;
  254. }
  255. /**
  256. * {@inheritdoc}
  257. */
  258. public function prune()
  259. {
  260. $pruned = true;
  261. foreach ($this->adapters as $adapter) {
  262. if ($adapter instanceof PruneableInterface) {
  263. $pruned = $adapter->prune() && $pruned;
  264. }
  265. }
  266. return $pruned;
  267. }
  268. /**
  269. * {@inheritdoc}
  270. */
  271. public function reset()
  272. {
  273. foreach ($this->adapters as $adapter) {
  274. if ($adapter instanceof ResetInterface) {
  275. $adapter->reset();
  276. }
  277. }
  278. }
  279. }