ArrayAdapter.php 8.4 KB

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