ArrayAdapter.php 11 KB

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