ProxyAdapter.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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 $namespace = '';
  27. private $namespaceLen;
  28. private $poolHash;
  29. private $defaultLifetime;
  30. private static $createCacheItem;
  31. private static $setInnerItem;
  32. public function __construct(CacheItemPoolInterface $pool, string $namespace = '', int $defaultLifetime = 0)
  33. {
  34. $this->pool = $pool;
  35. $this->poolHash = $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)
  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($key)
  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 = [])
  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. * @return bool
  129. */
  130. public function hasItem($key)
  131. {
  132. return $this->pool->hasItem($this->getId($key));
  133. }
  134. /**
  135. * {@inheritdoc}
  136. *
  137. * @return bool
  138. */
  139. public function clear(string $prefix = '')
  140. {
  141. if ($this->pool instanceof AdapterInterface) {
  142. return $this->pool->clear($this->namespace.$prefix);
  143. }
  144. return $this->pool->clear();
  145. }
  146. /**
  147. * {@inheritdoc}
  148. *
  149. * @return bool
  150. */
  151. public function deleteItem($key)
  152. {
  153. return $this->pool->deleteItem($this->getId($key));
  154. }
  155. /**
  156. * {@inheritdoc}
  157. *
  158. * @return bool
  159. */
  160. public function deleteItems(array $keys)
  161. {
  162. if ($this->namespaceLen) {
  163. foreach ($keys as $i => $key) {
  164. $keys[$i] = $this->getId($key);
  165. }
  166. }
  167. return $this->pool->deleteItems($keys);
  168. }
  169. /**
  170. * {@inheritdoc}
  171. *
  172. * @return bool
  173. */
  174. public function save(CacheItemInterface $item)
  175. {
  176. return $this->doSave($item, __FUNCTION__);
  177. }
  178. /**
  179. * {@inheritdoc}
  180. *
  181. * @return bool
  182. */
  183. public function saveDeferred(CacheItemInterface $item)
  184. {
  185. return $this->doSave($item, __FUNCTION__);
  186. }
  187. /**
  188. * {@inheritdoc}
  189. *
  190. * @return bool
  191. */
  192. public function commit()
  193. {
  194. return $this->pool->commit();
  195. }
  196. private function doSave(CacheItemInterface $item, string $method)
  197. {
  198. if (!$item instanceof CacheItem) {
  199. return false;
  200. }
  201. $item = (array) $item;
  202. if (null === $item["\0*\0expiry"] && 0 < $this->defaultLifetime) {
  203. $item["\0*\0expiry"] = microtime(true) + $this->defaultLifetime;
  204. }
  205. if ($item["\0*\0poolHash"] === $this->poolHash && $item["\0*\0innerItem"]) {
  206. $innerItem = $item["\0*\0innerItem"];
  207. } elseif ($this->pool instanceof AdapterInterface) {
  208. // this is an optimization specific for AdapterInterface implementations
  209. // so we can save a round-trip to the backend by just creating a new item
  210. $innerItem = (self::$createCacheItem)($this->namespace.$item["\0*\0key"], null, $this->poolHash);
  211. } else {
  212. $innerItem = $this->pool->getItem($this->namespace.$item["\0*\0key"]);
  213. }
  214. (self::$setInnerItem)($innerItem, $item);
  215. return $this->pool->$method($innerItem);
  216. }
  217. private function generateItems(iterable $items): \Generator
  218. {
  219. $f = self::$createCacheItem;
  220. foreach ($items as $key => $item) {
  221. if ($this->namespaceLen) {
  222. $key = substr($key, $this->namespaceLen);
  223. }
  224. yield $key => $f($key, $item, $this->poolHash);
  225. }
  226. }
  227. private function getId($key): string
  228. {
  229. \assert('' !== CacheItem::validateKey($key));
  230. return $this->namespace.$key;
  231. }
  232. }