ArrayAdapter.php 11 KB

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