ProxyAdapter.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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\PruneableInterface;
  15. use Symfony\Component\Cache\ResettableInterface;
  16. use Symfony\Component\Cache\Traits\ContractsTrait;
  17. use Symfony\Component\Cache\Traits\ProxyTrait;
  18. use Symfony\Contracts\Cache\CacheInterface;
  19. /**
  20. * @author Nicolas Grekas <p@tchwork.com>
  21. */
  22. class ProxyAdapter implements AdapterInterface, CacheInterface, PruneableInterface, ResettableInterface
  23. {
  24. use ContractsTrait;
  25. use ProxyTrait;
  26. private string $namespace = '';
  27. private int $namespaceLen;
  28. private string $poolHash;
  29. private int $defaultLifetime;
  30. private static \Closure $createCacheItem;
  31. private static \Closure $setInnerItem;
  32. public function __construct(CacheItemPoolInterface $pool, string $namespace = '', int $defaultLifetime = 0)
  33. {
  34. $this->pool = $pool;
  35. $this->poolHash = spl_object_hash($pool);
  36. if ('' !== $namespace) {
  37. \assert('' !== CacheItem::validateKey($namespace));
  38. $this->namespace = $namespace;
  39. }
  40. $this->namespaceLen = \strlen($namespace);
  41. $this->defaultLifetime = $defaultLifetime;
  42. self::$createCacheItem ?? self::$createCacheItem = \Closure::bind(
  43. static function ($key, $innerItem, $poolHash) {
  44. $item = new CacheItem();
  45. $item->key = $key;
  46. if (null === $innerItem) {
  47. return $item;
  48. }
  49. $item->value = $v = $innerItem->get();
  50. $item->isHit = $innerItem->isHit();
  51. $item->innerItem = $innerItem;
  52. $item->poolHash = $poolHash;
  53. // Detect wrapped values that encode for their expiry and creation duration
  54. // For compactness, these values are packed in the key of an array using
  55. // magic numbers in the form 9D-..-..-..-..-00-..-..-..-5F
  56. if (\is_array($v) && 1 === \count($v) && 10 === \strlen($k = (string) array_key_first($v)) && "\x9D" === $k[0] && "\0" === $k[5] && "\x5F" === $k[9]) {
  57. $item->value = $v[$k];
  58. $v = unpack('Ve/Nc', substr($k, 1, -1));
  59. $item->metadata[CacheItem::METADATA_EXPIRY] = $v['e'] + CacheItem::METADATA_EXPIRY_OFFSET;
  60. $item->metadata[CacheItem::METADATA_CTIME] = $v['c'];
  61. } elseif ($innerItem instanceof CacheItem) {
  62. $item->metadata = $innerItem->metadata;
  63. }
  64. $innerItem->set(null);
  65. return $item;
  66. },
  67. null,
  68. CacheItem::class
  69. );
  70. self::$setInnerItem ?? self::$setInnerItem = \Closure::bind(
  71. /**
  72. * @param array $item A CacheItem cast to (array); accessing protected properties requires adding the "\0*\0" PHP prefix
  73. */
  74. static function (CacheItemInterface $innerItem, array $item) {
  75. // Tags are stored separately, no need to account for them when considering this item's newly set metadata
  76. if (isset(($metadata = $item["\0*\0newMetadata"])[CacheItem::METADATA_TAGS])) {
  77. unset($metadata[CacheItem::METADATA_TAGS]);
  78. }
  79. if ($metadata) {
  80. // For compactness, expiry and creation duration are packed in the key of an array, using magic numbers as separators
  81. $item["\0*\0value"] = ["\x9D".pack('VN', (int) (0.1 + $metadata[self::METADATA_EXPIRY] - self::METADATA_EXPIRY_OFFSET), $metadata[self::METADATA_CTIME])."\x5F" => $item["\0*\0value"]];
  82. }
  83. $innerItem->set($item["\0*\0value"]);
  84. $innerItem->expiresAt(null !== $item["\0*\0expiry"] ? \DateTime::createFromFormat('U.u', sprintf('%.6F', $item["\0*\0expiry"])) : null);
  85. },
  86. null,
  87. CacheItem::class
  88. );
  89. }
  90. /**
  91. * {@inheritdoc}
  92. */
  93. public function get(string $key, callable $callback, float $beta = null, array &$metadata = null): mixed
  94. {
  95. if (!$this->pool instanceof CacheInterface) {
  96. return $this->doGet($this, $key, $callback, $beta, $metadata);
  97. }
  98. return $this->pool->get($this->getId($key), function ($innerItem, bool &$save) use ($key, $callback) {
  99. $item = (self::$createCacheItem)($key, $innerItem, $this->poolHash);
  100. $item->set($value = $callback($item, $save));
  101. (self::$setInnerItem)($innerItem, (array) $item);
  102. return $value;
  103. }, $beta, $metadata);
  104. }
  105. /**
  106. * {@inheritdoc}
  107. */
  108. public function getItem(mixed $key): CacheItem
  109. {
  110. $item = $this->pool->getItem($this->getId($key));
  111. return (self::$createCacheItem)($key, $item, $this->poolHash);
  112. }
  113. /**
  114. * {@inheritdoc}
  115. */
  116. public function getItems(array $keys = []): iterable
  117. {
  118. if ($this->namespaceLen) {
  119. foreach ($keys as $i => $key) {
  120. $keys[$i] = $this->getId($key);
  121. }
  122. }
  123. return $this->generateItems($this->pool->getItems($keys));
  124. }
  125. /**
  126. * {@inheritdoc}
  127. */
  128. public function hasItem(mixed $key): bool
  129. {
  130. return $this->pool->hasItem($this->getId($key));
  131. }
  132. /**
  133. * {@inheritdoc}
  134. */
  135. public function clear(string $prefix = ''): bool
  136. {
  137. if ($this->pool instanceof AdapterInterface) {
  138. return $this->pool->clear($this->namespace.$prefix);
  139. }
  140. return $this->pool->clear();
  141. }
  142. /**
  143. * {@inheritdoc}
  144. */
  145. public function deleteItem(mixed $key): bool
  146. {
  147. return $this->pool->deleteItem($this->getId($key));
  148. }
  149. /**
  150. * {@inheritdoc}
  151. */
  152. public function deleteItems(array $keys): bool
  153. {
  154. if ($this->namespaceLen) {
  155. foreach ($keys as $i => $key) {
  156. $keys[$i] = $this->getId($key);
  157. }
  158. }
  159. return $this->pool->deleteItems($keys);
  160. }
  161. /**
  162. * {@inheritdoc}
  163. */
  164. public function save(CacheItemInterface $item): bool
  165. {
  166. return $this->doSave($item, __FUNCTION__);
  167. }
  168. /**
  169. * {@inheritdoc}
  170. */
  171. public function saveDeferred(CacheItemInterface $item): bool
  172. {
  173. return $this->doSave($item, __FUNCTION__);
  174. }
  175. /**
  176. * {@inheritdoc}
  177. */
  178. public function commit(): bool
  179. {
  180. return $this->pool->commit();
  181. }
  182. private function doSave(CacheItemInterface $item, string $method): bool
  183. {
  184. if (!$item instanceof CacheItem) {
  185. return false;
  186. }
  187. $item = (array) $item;
  188. if (null === $item["\0*\0expiry"] && 0 < $this->defaultLifetime) {
  189. $item["\0*\0expiry"] = microtime(true) + $this->defaultLifetime;
  190. }
  191. if ($item["\0*\0poolHash"] === $this->poolHash && $item["\0*\0innerItem"]) {
  192. $innerItem = $item["\0*\0innerItem"];
  193. } elseif ($this->pool instanceof AdapterInterface) {
  194. // this is an optimization specific for AdapterInterface implementations
  195. // so we can save a round-trip to the backend by just creating a new item
  196. $innerItem = (self::$createCacheItem)($this->namespace.$item["\0*\0key"], null, $this->poolHash);
  197. } else {
  198. $innerItem = $this->pool->getItem($this->namespace.$item["\0*\0key"]);
  199. }
  200. (self::$setInnerItem)($innerItem, $item);
  201. return $this->pool->$method($innerItem);
  202. }
  203. private function generateItems(iterable $items): \Generator
  204. {
  205. $f = self::$createCacheItem;
  206. foreach ($items as $key => $item) {
  207. if ($this->namespaceLen) {
  208. $key = substr($key, $this->namespaceLen);
  209. }
  210. yield $key => $f($key, $item, $this->poolHash);
  211. }
  212. }
  213. private function getId(mixed $key): string
  214. {
  215. \assert('' !== CacheItem::validateKey($key));
  216. return $this->namespace.$key;
  217. }
  218. }