ArrayAdapter.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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\Clock\ClockInterface;
  13. use Psr\Log\LoggerAwareInterface;
  14. use Psr\Log\LoggerAwareTrait;
  15. use Symfony\Component\Cache\CacheItem;
  16. use Symfony\Component\Cache\Exception\InvalidArgumentException;
  17. use Symfony\Component\Cache\ResettableInterface;
  18. use Symfony\Contracts\Cache\CacheInterface;
  19. use Symfony\Contracts\Cache\NamespacedPoolInterface;
  20. /**
  21. * An in-memory cache storage.
  22. *
  23. * Acts as a least-recently-used (LRU) storage when configured with a maximum number of items.
  24. *
  25. * @author Nicolas Grekas <p@tchwork.com>
  26. */
  27. class ArrayAdapter implements AdapterInterface, CacheInterface, NamespacedPoolInterface, LoggerAwareInterface, ResettableInterface
  28. {
  29. use LoggerAwareTrait;
  30. private array $values = [];
  31. private array $tags = [];
  32. private array $expiries = [];
  33. private array $subPools = [];
  34. private static \Closure $createCacheItem;
  35. /**
  36. * @param bool $storeSerialized Disabling serialization can lead to cache corruptions when storing mutable values but increases performance otherwise
  37. */
  38. public function __construct(
  39. private int $defaultLifetime = 0,
  40. private bool $storeSerialized = true,
  41. private float $maxLifetime = 0,
  42. private int $maxItems = 0,
  43. private ?ClockInterface $clock = null,
  44. ) {
  45. if (0 > $maxLifetime) {
  46. throw new InvalidArgumentException(\sprintf('Argument $maxLifetime must be positive, %F passed.', $maxLifetime));
  47. }
  48. if (0 > $maxItems) {
  49. throw new InvalidArgumentException(\sprintf('Argument $maxItems must be a positive integer, %d passed.', $maxItems));
  50. }
  51. self::$createCacheItem ??= \Closure::bind(
  52. static function ($key, $value, $isHit, $tags) {
  53. $item = new CacheItem();
  54. $item->key = $key;
  55. $item->value = $value;
  56. $item->isHit = $isHit;
  57. if (null !== $tags) {
  58. $item->metadata[CacheItem::METADATA_TAGS] = $tags;
  59. }
  60. return $item;
  61. },
  62. null,
  63. CacheItem::class
  64. );
  65. }
  66. public function get(string $key, callable $callback, ?float $beta = null, ?array &$metadata = null): mixed
  67. {
  68. $item = $this->getItem($key);
  69. $metadata = $item->getMetadata();
  70. // ArrayAdapter works in memory, we don't care about stampede protection
  71. if (\INF === $beta || !$item->isHit()) {
  72. $save = true;
  73. $item->set($callback($item, $save));
  74. if ($save) {
  75. $this->save($item);
  76. }
  77. }
  78. return $item->get();
  79. }
  80. public function delete(string $key): bool
  81. {
  82. return $this->deleteItem($key);
  83. }
  84. public function hasItem(mixed $key): bool
  85. {
  86. if (\is_string($key) && isset($this->expiries[$key]) && $this->expiries[$key] > $this->getCurrentTime()) {
  87. if ($this->maxItems) {
  88. // Move the item last in the storage
  89. $value = $this->values[$key];
  90. unset($this->values[$key]);
  91. $this->values[$key] = $value;
  92. }
  93. return true;
  94. }
  95. \assert('' !== CacheItem::validateKey($key));
  96. return isset($this->expiries[$key]) && !$this->deleteItem($key);
  97. }
  98. public function getItem(mixed $key): CacheItem
  99. {
  100. if (!$isHit = $this->hasItem($key)) {
  101. $value = null;
  102. if (!$this->maxItems) {
  103. // Track misses in non-LRU mode only
  104. $this->values[$key] = null;
  105. }
  106. } else {
  107. $value = $this->storeSerialized ? $this->unfreeze($key, $isHit) : $this->values[$key];
  108. }
  109. return (self::$createCacheItem)($key, $value, $isHit, $this->tags[$key] ?? null);
  110. }
  111. public function getItems(array $keys = []): iterable
  112. {
  113. \assert(self::validateKeys($keys));
  114. return $this->generateItems($keys, $this->getCurrentTime(), self::$createCacheItem);
  115. }
  116. public function deleteItem(mixed $key): bool
  117. {
  118. \assert('' !== CacheItem::validateKey($key));
  119. unset($this->values[$key], $this->tags[$key], $this->expiries[$key]);
  120. return true;
  121. }
  122. public function deleteItems(array $keys): bool
  123. {
  124. foreach ($keys as $key) {
  125. $this->deleteItem($key);
  126. }
  127. return true;
  128. }
  129. public function save(CacheItemInterface $item): bool
  130. {
  131. if (!$item instanceof CacheItem) {
  132. return false;
  133. }
  134. $item = (array) $item;
  135. $key = $item["\0*\0key"];
  136. $value = $item["\0*\0value"];
  137. $expiry = $item["\0*\0expiry"];
  138. $now = $this->getCurrentTime();
  139. if (null !== $expiry) {
  140. if (!$expiry) {
  141. $expiry = \PHP_INT_MAX;
  142. } elseif ($expiry <= $now) {
  143. $this->deleteItem($key);
  144. return true;
  145. }
  146. }
  147. if ($this->storeSerialized && null === $value = $this->freeze($value, $key)) {
  148. return false;
  149. }
  150. if (null === $expiry && 0 < $this->defaultLifetime) {
  151. $expiry = $this->defaultLifetime;
  152. $expiry = $now + ($expiry > ($this->maxLifetime ?: $expiry) ? $this->maxLifetime : $expiry);
  153. } elseif ($this->maxLifetime && (null === $expiry || $expiry > $now + $this->maxLifetime)) {
  154. $expiry = $now + $this->maxLifetime;
  155. }
  156. if ($this->maxItems) {
  157. unset($this->values[$key], $this->tags[$key]);
  158. // Iterate items and vacuum expired ones while we are at it
  159. foreach ($this->values as $k => $v) {
  160. if ($this->expiries[$k] > $now && \count($this->values) < $this->maxItems) {
  161. break;
  162. }
  163. unset($this->values[$k], $this->tags[$k], $this->expiries[$k]);
  164. }
  165. }
  166. $this->values[$key] = $value;
  167. $this->expiries[$key] = $expiry ?? \PHP_INT_MAX;
  168. if (null === $this->tags[$key] = $item["\0*\0newMetadata"][CacheItem::METADATA_TAGS] ?? null) {
  169. unset($this->tags[$key]);
  170. }
  171. return true;
  172. }
  173. public function saveDeferred(CacheItemInterface $item): bool
  174. {
  175. return $this->save($item);
  176. }
  177. public function commit(): bool
  178. {
  179. return true;
  180. }
  181. public function clear(string $prefix = ''): bool
  182. {
  183. if ('' !== $prefix) {
  184. $now = $this->getCurrentTime();
  185. foreach ($this->values as $key => $value) {
  186. if (!isset($this->expiries[$key]) || $this->expiries[$key] <= $now || str_starts_with($key, $prefix)) {
  187. unset($this->values[$key], $this->tags[$key], $this->expiries[$key]);
  188. }
  189. }
  190. return true;
  191. }
  192. foreach ($this->subPools as $pool) {
  193. $pool->clear();
  194. }
  195. $this->subPools = $this->values = $this->tags = $this->expiries = [];
  196. return true;
  197. }
  198. public function withSubNamespace(string $namespace): static
  199. {
  200. CacheItem::validateKey($namespace);
  201. $subPools = $this->subPools;
  202. if (isset($subPools[$namespace])) {
  203. return $subPools[$namespace];
  204. }
  205. $this->subPools = [];
  206. $clone = clone $this;
  207. $clone->clear();
  208. $subPools[$namespace] = $clone;
  209. $this->subPools = $subPools;
  210. return $clone;
  211. }
  212. /**
  213. * Returns all cached values, with cache miss as null.
  214. */
  215. public function getValues(): array
  216. {
  217. if (!$this->storeSerialized) {
  218. return $this->values;
  219. }
  220. $values = $this->values;
  221. foreach ($values as $k => $v) {
  222. if (null === $v || 'N;' === $v) {
  223. continue;
  224. }
  225. if (!\is_string($v) || !isset($v[2]) || ':' !== $v[1]) {
  226. $values[$k] = serialize($v);
  227. }
  228. }
  229. return $values;
  230. }
  231. public function reset(): void
  232. {
  233. $this->clear();
  234. }
  235. public function __clone()
  236. {
  237. foreach ($this->subPools as $i => $pool) {
  238. $this->subPools[$i] = clone $pool;
  239. }
  240. }
  241. private function generateItems(array $keys, float $now, \Closure $f): \Generator
  242. {
  243. foreach ($keys as $i => $key) {
  244. if (!$isHit = isset($this->expiries[$key]) && ($this->expiries[$key] > $now || !$this->deleteItem($key))) {
  245. $value = null;
  246. if (!$this->maxItems) {
  247. // Track misses in non-LRU mode only
  248. $this->values[$key] = null;
  249. }
  250. } else {
  251. if ($this->maxItems) {
  252. // Move the item last in the storage
  253. $value = $this->values[$key];
  254. unset($this->values[$key]);
  255. $this->values[$key] = $value;
  256. }
  257. $value = $this->storeSerialized ? $this->unfreeze($key, $isHit) : $this->values[$key];
  258. }
  259. unset($keys[$i]);
  260. yield $key => $f($key, $value, $isHit, $this->tags[$key] ?? null);
  261. }
  262. foreach ($keys as $key) {
  263. yield $key => $f($key, null, false);
  264. }
  265. }
  266. private function freeze($value, string $key): string|int|float|bool|array|\UnitEnum|null
  267. {
  268. if (null === $value) {
  269. return 'N;';
  270. }
  271. if (\is_string($value)) {
  272. // Serialize strings if they could be confused with serialized objects or arrays
  273. if ('N;' === $value || (isset($value[2]) && ':' === $value[1])) {
  274. return serialize($value);
  275. }
  276. } elseif (!\is_scalar($value)) {
  277. try {
  278. $serialized = serialize($value);
  279. } catch (\Exception $e) {
  280. if (!isset($this->expiries[$key])) {
  281. unset($this->values[$key]);
  282. }
  283. $type = get_debug_type($value);
  284. $message = \sprintf('Failed to save key "{key}" of type %s: %s', $type, $e->getMessage());
  285. CacheItem::log($this->logger, $message, ['key' => $key, 'exception' => $e, 'cache-adapter' => get_debug_type($this)]);
  286. return null;
  287. }
  288. // Keep value serialized if it contains any objects or any internal references
  289. if ('C' === $serialized[0] || 'O' === $serialized[0] || preg_match('/;[OCRr]:[1-9]/', $serialized)) {
  290. return $serialized;
  291. }
  292. }
  293. return $value;
  294. }
  295. private function unfreeze(string $key, bool &$isHit): mixed
  296. {
  297. if ('N;' === $value = $this->values[$key]) {
  298. return null;
  299. }
  300. if (\is_string($value) && isset($value[2]) && ':' === $value[1]) {
  301. try {
  302. $value = unserialize($value);
  303. } catch (\Exception $e) {
  304. CacheItem::log($this->logger, 'Failed to unserialize key "{key}": '.$e->getMessage(), ['key' => $key, 'exception' => $e, 'cache-adapter' => get_debug_type($this)]);
  305. $value = false;
  306. }
  307. if (false === $value) {
  308. $value = null;
  309. $isHit = false;
  310. if (!$this->maxItems) {
  311. $this->values[$key] = null;
  312. }
  313. }
  314. }
  315. return $value;
  316. }
  317. private function validateKeys(array $keys): bool
  318. {
  319. foreach ($keys as $key) {
  320. if (!\is_string($key) || !isset($this->expiries[$key])) {
  321. CacheItem::validateKey($key);
  322. }
  323. }
  324. return true;
  325. }
  326. private function getCurrentTime(): float
  327. {
  328. return $this->clock?->now()->format('U.u') ?? microtime(true);
  329. }
  330. }