ArrayAdapter.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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 $storeSerialized;
  29. private $values = [];
  30. private $expiries = [];
  31. private $defaultLifetime;
  32. private $maxLifetime;
  33. private $maxItems;
  34. private static $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)
  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. $this->save($item->set($callback($item, $save)));
  73. }
  74. return $item->get();
  75. }
  76. /**
  77. * {@inheritdoc}
  78. */
  79. public function delete(string $key): bool
  80. {
  81. return $this->deleteItem($key);
  82. }
  83. /**
  84. * {@inheritdoc}
  85. *
  86. * @return bool
  87. */
  88. public function hasItem($key)
  89. {
  90. if (\is_string($key) && isset($this->expiries[$key]) && $this->expiries[$key] > microtime(true)) {
  91. if ($this->maxItems) {
  92. // Move the item last in the storage
  93. $value = $this->values[$key];
  94. unset($this->values[$key]);
  95. $this->values[$key] = $value;
  96. }
  97. return true;
  98. }
  99. \assert('' !== CacheItem::validateKey($key));
  100. return isset($this->expiries[$key]) && !$this->deleteItem($key);
  101. }
  102. /**
  103. * {@inheritdoc}
  104. */
  105. public function getItem($key)
  106. {
  107. if (!$isHit = $this->hasItem($key)) {
  108. $value = null;
  109. if (!$this->maxItems) {
  110. // Track misses in non-LRU mode only
  111. $this->values[$key] = null;
  112. }
  113. } else {
  114. $value = $this->storeSerialized ? $this->unfreeze($key, $isHit) : $this->values[$key];
  115. }
  116. return (self::$createCacheItem)($key, $value, $isHit);
  117. }
  118. /**
  119. * {@inheritdoc}
  120. */
  121. public function getItems(array $keys = [])
  122. {
  123. \assert(self::validateKeys($keys));
  124. return $this->generateItems($keys, microtime(true), self::$createCacheItem);
  125. }
  126. /**
  127. * {@inheritdoc}
  128. *
  129. * @return bool
  130. */
  131. public function deleteItem($key)
  132. {
  133. \assert('' !== CacheItem::validateKey($key));
  134. unset($this->values[$key], $this->expiries[$key]);
  135. return true;
  136. }
  137. /**
  138. * {@inheritdoc}
  139. *
  140. * @return bool
  141. */
  142. public function deleteItems(array $keys)
  143. {
  144. foreach ($keys as $key) {
  145. $this->deleteItem($key);
  146. }
  147. return true;
  148. }
  149. /**
  150. * {@inheritdoc}
  151. *
  152. * @return bool
  153. */
  154. public function save(CacheItemInterface $item)
  155. {
  156. if (!$item instanceof CacheItem) {
  157. return false;
  158. }
  159. $item = (array) $item;
  160. $key = $item["\0*\0key"];
  161. $value = $item["\0*\0value"];
  162. $expiry = $item["\0*\0expiry"];
  163. $now = microtime(true);
  164. if (0 === $expiry) {
  165. $expiry = \PHP_INT_MAX;
  166. }
  167. if (null !== $expiry && $expiry <= $now) {
  168. $this->deleteItem($key);
  169. return true;
  170. }
  171. if ($this->storeSerialized && null === $value = $this->freeze($value, $key)) {
  172. return false;
  173. }
  174. if (null === $expiry && 0 < $this->defaultLifetime) {
  175. $expiry = $this->defaultLifetime;
  176. $expiry = $now + ($expiry > ($this->maxLifetime ?: $expiry) ? $this->maxLifetime : $expiry);
  177. } elseif ($this->maxLifetime && (null === $expiry || $expiry > $now + $this->maxLifetime)) {
  178. $expiry = $now + $this->maxLifetime;
  179. }
  180. if ($this->maxItems) {
  181. unset($this->values[$key]);
  182. // Iterate items and vacuum expired ones while we are at it
  183. foreach ($this->values as $k => $v) {
  184. if ($this->expiries[$k] > $now && \count($this->values) < $this->maxItems) {
  185. break;
  186. }
  187. unset($this->values[$k], $this->expiries[$k]);
  188. }
  189. }
  190. $this->values[$key] = $value;
  191. $this->expiries[$key] = $expiry ?? \PHP_INT_MAX;
  192. return true;
  193. }
  194. /**
  195. * {@inheritdoc}
  196. *
  197. * @return bool
  198. */
  199. public function saveDeferred(CacheItemInterface $item)
  200. {
  201. return $this->save($item);
  202. }
  203. /**
  204. * {@inheritdoc}
  205. *
  206. * @return bool
  207. */
  208. public function commit()
  209. {
  210. return true;
  211. }
  212. /**
  213. * {@inheritdoc}
  214. *
  215. * @return bool
  216. */
  217. public function clear(string $prefix = '')
  218. {
  219. if ('' !== $prefix) {
  220. $now = microtime(true);
  221. foreach ($this->values as $key => $value) {
  222. if (!isset($this->expiries[$key]) || $this->expiries[$key] <= $now || 0 === strpos($key, $prefix)) {
  223. unset($this->values[$key], $this->expiries[$key]);
  224. }
  225. }
  226. if ($this->values) {
  227. return true;
  228. }
  229. }
  230. $this->values = $this->expiries = [];
  231. return true;
  232. }
  233. /**
  234. * Returns all cached values, with cache miss as null.
  235. *
  236. * @return array
  237. */
  238. public function getValues()
  239. {
  240. if (!$this->storeSerialized) {
  241. return $this->values;
  242. }
  243. $values = $this->values;
  244. foreach ($values as $k => $v) {
  245. if (null === $v || 'N;' === $v) {
  246. continue;
  247. }
  248. if (!\is_string($v) || !isset($v[2]) || ':' !== $v[1]) {
  249. $values[$k] = serialize($v);
  250. }
  251. }
  252. return $values;
  253. }
  254. /**
  255. * {@inheritdoc}
  256. */
  257. public function reset()
  258. {
  259. $this->clear();
  260. }
  261. private function generateItems(array $keys, float $now, \Closure $f): \Generator
  262. {
  263. foreach ($keys as $i => $key) {
  264. if (!$isHit = isset($this->expiries[$key]) && ($this->expiries[$key] > $now || !$this->deleteItem($key))) {
  265. $value = null;
  266. if (!$this->maxItems) {
  267. // Track misses in non-LRU mode only
  268. $this->values[$key] = null;
  269. }
  270. } else {
  271. if ($this->maxItems) {
  272. // Move the item last in the storage
  273. $value = $this->values[$key];
  274. unset($this->values[$key]);
  275. $this->values[$key] = $value;
  276. }
  277. $value = $this->storeSerialized ? $this->unfreeze($key, $isHit) : $this->values[$key];
  278. }
  279. unset($keys[$i]);
  280. yield $key => $f($key, $value, $isHit);
  281. }
  282. foreach ($keys as $key) {
  283. yield $key => $f($key, null, false);
  284. }
  285. }
  286. private function freeze($value, string $key)
  287. {
  288. if (null === $value) {
  289. return 'N;';
  290. }
  291. if (\is_string($value)) {
  292. // Serialize strings if they could be confused with serialized objects or arrays
  293. if ('N;' === $value || (isset($value[2]) && ':' === $value[1])) {
  294. return serialize($value);
  295. }
  296. } elseif (!is_scalar($value)) {
  297. try {
  298. $serialized = serialize($value);
  299. } catch (\Exception $e) {
  300. unset($this->values[$key]);
  301. $type = get_debug_type($value);
  302. $message = sprintf('Failed to save key "{key}" of type %s: %s', $type, $e->getMessage());
  303. CacheItem::log($this->logger, $message, ['key' => $key, 'exception' => $e, 'cache-adapter' => get_debug_type($this)]);
  304. return;
  305. }
  306. // Keep value serialized if it contains any objects or any internal references
  307. if ('C' === $serialized[0] || 'O' === $serialized[0] || preg_match('/;[OCRr]:[1-9]/', $serialized)) {
  308. return $serialized;
  309. }
  310. }
  311. return $value;
  312. }
  313. private function unfreeze(string $key, bool &$isHit)
  314. {
  315. if ('N;' === $value = $this->values[$key]) {
  316. return null;
  317. }
  318. if (\is_string($value) && isset($value[2]) && ':' === $value[1]) {
  319. try {
  320. $value = unserialize($value);
  321. } catch (\Exception $e) {
  322. CacheItem::log($this->logger, 'Failed to unserialize key "{key}": '.$e->getMessage(), ['key' => $key, 'exception' => $e, 'cache-adapter' => get_debug_type($this)]);
  323. $value = false;
  324. }
  325. if (false === $value) {
  326. $value = null;
  327. $isHit = false;
  328. if (!$this->maxItems) {
  329. $this->values[$key] = null;
  330. }
  331. }
  332. }
  333. return $value;
  334. }
  335. private function validateKeys(array $keys): bool
  336. {
  337. foreach ($keys as $key) {
  338. if (!\is_string($key) || !isset($this->expiries[$key])) {
  339. CacheItem::validateKey($key);
  340. }
  341. }
  342. return true;
  343. }
  344. }