ArrayAdapter.php 11 KB

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