PhpArrayAdapter.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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\Cache\CacheItemPoolInterface;
  13. use Symfony\Component\Cache\CacheItem;
  14. use Symfony\Component\Cache\Exception\InvalidArgumentException;
  15. use Symfony\Component\Cache\PruneableInterface;
  16. use Symfony\Component\Cache\ResettableInterface;
  17. use Symfony\Component\Cache\Traits\ContractsTrait;
  18. use Symfony\Component\Cache\Traits\ProxyTrait;
  19. use Symfony\Component\VarExporter\VarExporter;
  20. use Symfony\Contracts\Cache\CacheInterface;
  21. /**
  22. * Caches items at warm up time using a PHP array that is stored in shared memory by OPCache since PHP 7.0.
  23. * Warmed up items are read-only and run-time discovered items are cached using a fallback adapter.
  24. *
  25. * @author Titouan Galopin <galopintitouan@gmail.com>
  26. * @author Nicolas Grekas <p@tchwork.com>
  27. */
  28. class PhpArrayAdapter implements AdapterInterface, CacheInterface, PruneableInterface, ResettableInterface
  29. {
  30. use ContractsTrait;
  31. use ProxyTrait;
  32. private $file;
  33. private $keys;
  34. private $values;
  35. private $createCacheItem;
  36. private static $valuesCache = [];
  37. /**
  38. * @param string $file The PHP file were values are cached
  39. * @param AdapterInterface $fallbackPool A pool to fallback on when an item is not hit
  40. */
  41. public function __construct(string $file, AdapterInterface $fallbackPool)
  42. {
  43. $this->file = $file;
  44. $this->pool = $fallbackPool;
  45. $this->createCacheItem = \Closure::bind(
  46. static function ($key, $value, $isHit) {
  47. $item = new CacheItem();
  48. $item->key = $key;
  49. $item->value = $value;
  50. $item->isHit = $isHit;
  51. return $item;
  52. },
  53. null,
  54. CacheItem::class
  55. );
  56. }
  57. /**
  58. * This adapter takes advantage of how PHP stores arrays in its latest versions.
  59. *
  60. * @param string $file The PHP file were values are cached
  61. * @param CacheItemPoolInterface $fallbackPool A pool to fallback on when an item is not hit
  62. *
  63. * @return CacheItemPoolInterface
  64. */
  65. public static function create(string $file, CacheItemPoolInterface $fallbackPool)
  66. {
  67. if (!$fallbackPool instanceof AdapterInterface) {
  68. $fallbackPool = new ProxyAdapter($fallbackPool);
  69. }
  70. return new static($file, $fallbackPool);
  71. }
  72. /**
  73. * {@inheritdoc}
  74. */
  75. public function get(string $key, callable $callback, float $beta = null, array &$metadata = null)
  76. {
  77. if (null === $this->values) {
  78. $this->initialize();
  79. }
  80. if (!isset($this->keys[$key])) {
  81. get_from_pool:
  82. if ($this->pool instanceof CacheInterface) {
  83. return $this->pool->get($key, $callback, $beta, $metadata);
  84. }
  85. return $this->doGet($this->pool, $key, $callback, $beta, $metadata);
  86. }
  87. $value = $this->values[$this->keys[$key]];
  88. if ('N;' === $value) {
  89. return null;
  90. }
  91. try {
  92. if ($value instanceof \Closure) {
  93. return $value();
  94. }
  95. } catch (\Throwable $e) {
  96. unset($this->keys[$key]);
  97. goto get_from_pool;
  98. }
  99. return $value;
  100. }
  101. /**
  102. * {@inheritdoc}
  103. */
  104. public function getItem($key)
  105. {
  106. if (!\is_string($key)) {
  107. throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', \is_object($key) ? \get_class($key) : \gettype($key)));
  108. }
  109. if (null === $this->values) {
  110. $this->initialize();
  111. }
  112. if (!isset($this->keys[$key])) {
  113. return $this->pool->getItem($key);
  114. }
  115. $value = $this->values[$this->keys[$key]];
  116. $isHit = true;
  117. if ('N;' === $value) {
  118. $value = null;
  119. } elseif ($value instanceof \Closure) {
  120. try {
  121. $value = $value();
  122. } catch (\Throwable $e) {
  123. $value = null;
  124. $isHit = false;
  125. }
  126. }
  127. $f = $this->createCacheItem;
  128. return $f($key, $value, $isHit);
  129. }
  130. /**
  131. * {@inheritdoc}
  132. */
  133. public function getItems(array $keys = [])
  134. {
  135. foreach ($keys as $key) {
  136. if (!\is_string($key)) {
  137. throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', \is_object($key) ? \get_class($key) : \gettype($key)));
  138. }
  139. }
  140. if (null === $this->values) {
  141. $this->initialize();
  142. }
  143. return $this->generateItems($keys);
  144. }
  145. /**
  146. * {@inheritdoc}
  147. *
  148. * @return bool
  149. */
  150. public function hasItem($key)
  151. {
  152. if (!\is_string($key)) {
  153. throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', \is_object($key) ? \get_class($key) : \gettype($key)));
  154. }
  155. if (null === $this->values) {
  156. $this->initialize();
  157. }
  158. return isset($this->keys[$key]) || $this->pool->hasItem($key);
  159. }
  160. /**
  161. * {@inheritdoc}
  162. *
  163. * @return bool
  164. */
  165. public function deleteItem($key)
  166. {
  167. if (!\is_string($key)) {
  168. throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', \is_object($key) ? \get_class($key) : \gettype($key)));
  169. }
  170. if (null === $this->values) {
  171. $this->initialize();
  172. }
  173. return !isset($this->keys[$key]) && $this->pool->deleteItem($key);
  174. }
  175. /**
  176. * {@inheritdoc}
  177. *
  178. * @return bool
  179. */
  180. public function deleteItems(array $keys)
  181. {
  182. $deleted = true;
  183. $fallbackKeys = [];
  184. foreach ($keys as $key) {
  185. if (!\is_string($key)) {
  186. throw new InvalidArgumentException(sprintf('Cache key must be string, "%s" given.', \is_object($key) ? \get_class($key) : \gettype($key)));
  187. }
  188. if (isset($this->keys[$key])) {
  189. $deleted = false;
  190. } else {
  191. $fallbackKeys[] = $key;
  192. }
  193. }
  194. if (null === $this->values) {
  195. $this->initialize();
  196. }
  197. if ($fallbackKeys) {
  198. $deleted = $this->pool->deleteItems($fallbackKeys) && $deleted;
  199. }
  200. return $deleted;
  201. }
  202. /**
  203. * {@inheritdoc}
  204. *
  205. * @return bool
  206. */
  207. public function save(CacheItemInterface $item)
  208. {
  209. if (null === $this->values) {
  210. $this->initialize();
  211. }
  212. return !isset($this->keys[$item->getKey()]) && $this->pool->save($item);
  213. }
  214. /**
  215. * {@inheritdoc}
  216. *
  217. * @return bool
  218. */
  219. public function saveDeferred(CacheItemInterface $item)
  220. {
  221. if (null === $this->values) {
  222. $this->initialize();
  223. }
  224. return !isset($this->keys[$item->getKey()]) && $this->pool->saveDeferred($item);
  225. }
  226. /**
  227. * {@inheritdoc}
  228. *
  229. * @return bool
  230. */
  231. public function commit()
  232. {
  233. return $this->pool->commit();
  234. }
  235. /**
  236. * {@inheritdoc}
  237. *
  238. * @return bool
  239. */
  240. public function clear(string $prefix = '')
  241. {
  242. $this->keys = $this->values = [];
  243. $cleared = @unlink($this->file) || !file_exists($this->file);
  244. unset(self::$valuesCache[$this->file]);
  245. if ($this->pool instanceof AdapterInterface) {
  246. return $this->pool->clear($prefix) && $cleared;
  247. }
  248. return $this->pool->clear() && $cleared;
  249. }
  250. /**
  251. * Store an array of cached values.
  252. *
  253. * @param array $values The cached values
  254. */
  255. public function warmUp(array $values)
  256. {
  257. if (file_exists($this->file)) {
  258. if (!is_file($this->file)) {
  259. throw new InvalidArgumentException(sprintf('Cache path exists and is not a file: %s.', $this->file));
  260. }
  261. if (!is_writable($this->file)) {
  262. throw new InvalidArgumentException(sprintf('Cache file is not writable: %s.', $this->file));
  263. }
  264. } else {
  265. $directory = \dirname($this->file);
  266. if (!is_dir($directory) && !@mkdir($directory, 0777, true)) {
  267. throw new InvalidArgumentException(sprintf('Cache directory does not exist and cannot be created: %s.', $directory));
  268. }
  269. if (!is_writable($directory)) {
  270. throw new InvalidArgumentException(sprintf('Cache directory is not writable: %s.', $directory));
  271. }
  272. }
  273. $dumpedValues = '';
  274. $dumpedMap = [];
  275. $dump = <<<'EOF'
  276. <?php
  277. // This file has been auto-generated by the Symfony Cache Component.
  278. return [[
  279. EOF;
  280. foreach ($values as $key => $value) {
  281. CacheItem::validateKey(\is_int($key) ? (string) $key : $key);
  282. $isStaticValue = true;
  283. if (null === $value) {
  284. $value = "'N;'";
  285. } elseif (\is_object($value) || \is_array($value)) {
  286. try {
  287. $value = VarExporter::export($value, $isStaticValue);
  288. } catch (\Exception $e) {
  289. throw new InvalidArgumentException(sprintf('Cache key "%s" has non-serializable %s value.', $key, \is_object($value) ? \get_class($value) : 'array'), 0, $e);
  290. }
  291. } elseif (\is_string($value)) {
  292. // Wrap "N;" in a closure to not confuse it with an encoded `null`
  293. if ('N;' === $value) {
  294. $isStaticValue = false;
  295. }
  296. $value = var_export($value, true);
  297. } elseif (!is_scalar($value)) {
  298. throw new InvalidArgumentException(sprintf('Cache key "%s" has non-serializable %s value.', $key, \gettype($value)));
  299. } else {
  300. $value = var_export($value, true);
  301. }
  302. if (!$isStaticValue) {
  303. $value = str_replace("\n", "\n ", $value);
  304. $value = "static function () {\n return {$value};\n}";
  305. }
  306. $hash = hash('md5', $value);
  307. if (null === $id = $dumpedMap[$hash] ?? null) {
  308. $id = $dumpedMap[$hash] = \count($dumpedMap);
  309. $dumpedValues .= "{$id} => {$value},\n";
  310. }
  311. $dump .= var_export($key, true)." => {$id},\n";
  312. }
  313. $dump .= "\n], [\n\n{$dumpedValues}\n]];\n";
  314. $tmpFile = uniqid($this->file, true);
  315. file_put_contents($tmpFile, $dump);
  316. @chmod($tmpFile, 0666 & ~umask());
  317. unset($serialized, $value, $dump);
  318. @rename($tmpFile, $this->file);
  319. unset(self::$valuesCache[$this->file]);
  320. $this->initialize();
  321. }
  322. /**
  323. * Load the cache file.
  324. */
  325. private function initialize()
  326. {
  327. if (isset(self::$valuesCache[$this->file])) {
  328. $values = self::$valuesCache[$this->file];
  329. } elseif (!file_exists($this->file)) {
  330. $this->keys = $this->values = [];
  331. return;
  332. } else {
  333. $values = self::$valuesCache[$this->file] = (include $this->file) ?: [[], []];
  334. }
  335. if (2 !== \count($values) || !isset($values[0], $values[1])) {
  336. $this->keys = $this->values = [];
  337. } else {
  338. list($this->keys, $this->values) = $values;
  339. }
  340. }
  341. private function generateItems(array $keys): \Generator
  342. {
  343. $f = $this->createCacheItem;
  344. $fallbackKeys = [];
  345. foreach ($keys as $key) {
  346. if (isset($this->keys[$key])) {
  347. $value = $this->values[$this->keys[$key]];
  348. if ('N;' === $value) {
  349. yield $key => $f($key, null, true);
  350. } elseif ($value instanceof \Closure) {
  351. try {
  352. yield $key => $f($key, $value(), true);
  353. } catch (\Throwable $e) {
  354. yield $key => $f($key, null, false);
  355. }
  356. } else {
  357. yield $key => $f($key, $value, true);
  358. }
  359. } else {
  360. $fallbackKeys[] = $key;
  361. }
  362. }
  363. if ($fallbackKeys) {
  364. yield from $this->pool->getItems($fallbackKeys);
  365. }
  366. }
  367. }