PhpFilesAdapter.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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 Symfony\Component\Cache\Exception\CacheException;
  12. use Symfony\Component\Cache\Exception\InvalidArgumentException;
  13. use Symfony\Component\Cache\PruneableInterface;
  14. use Symfony\Component\Cache\Traits\CachedValueInterface;
  15. use Symfony\Component\Cache\Traits\FilesystemCommonTrait;
  16. use Symfony\Component\VarExporter\VarExporter;
  17. /**
  18. * @author Piotr Stankowski <git@trakos.pl>
  19. * @author Nicolas Grekas <p@tchwork.com>
  20. * @author Rob Frawley 2nd <rmf@src.run>
  21. */
  22. class PhpFilesAdapter extends AbstractAdapter implements PruneableInterface
  23. {
  24. use FilesystemCommonTrait {
  25. doClear as private doCommonClear;
  26. doDelete as private doCommonDelete;
  27. }
  28. private \Closure $includeHandler;
  29. private array $values = [];
  30. private array $files = [];
  31. private static int $startTime;
  32. private static array $valuesCache = [];
  33. /**
  34. * @param bool $appendOnly Set to `true` to gain extra performance when the items stored in this pool never expire.
  35. * Doing so is encouraged because it fits perfectly OPcache's memory model.
  36. *
  37. * @throws CacheException if OPcache is not enabled
  38. */
  39. public function __construct(
  40. string $namespace = '',
  41. int $defaultLifetime = 0,
  42. ?string $directory = null,
  43. private bool $appendOnly = false,
  44. ) {
  45. self::$startTime ??= $_SERVER['REQUEST_TIME'] ?? time();
  46. parent::__construct('', $defaultLifetime);
  47. $this->init($namespace, $directory);
  48. $this->includeHandler = static function ($type, $msg, $file, $line) {
  49. throw new \ErrorException($msg, 0, $type, $file, $line);
  50. };
  51. }
  52. public static function isSupported(): bool
  53. {
  54. self::$startTime ??= $_SERVER['REQUEST_TIME'] ?? time();
  55. return \function_exists('opcache_invalidate') && filter_var(\ini_get('opcache.enable'), \FILTER_VALIDATE_BOOL) && (!\in_array(\PHP_SAPI, ['cli', 'phpdbg', 'embed'], true) || filter_var(\ini_get('opcache.enable_cli'), \FILTER_VALIDATE_BOOL));
  56. }
  57. public function prune(): bool
  58. {
  59. $time = time();
  60. $pruned = true;
  61. $getExpiry = true;
  62. set_error_handler($this->includeHandler);
  63. try {
  64. foreach ($this->scanHashDir($this->directory) as $file) {
  65. try {
  66. if (\is_array($expiresAt = include $file)) {
  67. $expiresAt = $expiresAt[0];
  68. }
  69. } catch (\ErrorException $e) {
  70. $expiresAt = $time;
  71. }
  72. if ($time >= $expiresAt) {
  73. $pruned = ($this->doUnlink($file) || !file_exists($file)) && $pruned;
  74. }
  75. }
  76. } finally {
  77. restore_error_handler();
  78. }
  79. return $pruned;
  80. }
  81. protected function doFetch(array $ids): iterable
  82. {
  83. if ($this->appendOnly) {
  84. $now = 0;
  85. $missingIds = [];
  86. } else {
  87. $now = time();
  88. $missingIds = $ids;
  89. $ids = [];
  90. }
  91. $values = [];
  92. while (true) {
  93. $getExpiry = false;
  94. foreach ($ids as $id) {
  95. if (null === $value = $this->values[$id] ?? null) {
  96. $missingIds[] = $id;
  97. } elseif ('N;' === $value) {
  98. $values[$id] = null;
  99. } elseif (!\is_object($value)) {
  100. $values[$id] = $value;
  101. } elseif ($value instanceof CachedValueInterface) {
  102. $values[$id] = $value->getValue();
  103. } elseif (!$value instanceof LazyValue) {
  104. $values[$id] = $value;
  105. } elseif (false === $values[$id] = include $value->file) {
  106. unset($values[$id], $this->values[$id]);
  107. $missingIds[] = $id;
  108. }
  109. if (!$this->appendOnly) {
  110. unset($this->values[$id]);
  111. }
  112. }
  113. if (!$missingIds) {
  114. return $values;
  115. }
  116. set_error_handler($this->includeHandler);
  117. try {
  118. $getExpiry = true;
  119. foreach ($missingIds as $k => $id) {
  120. try {
  121. $file = $this->files[$id] ??= $this->getFile($id);
  122. if (isset(self::$valuesCache[$file])) {
  123. [$expiresAt, $this->values[$id]] = self::$valuesCache[$file];
  124. } elseif (\is_array($expiresAt = include $file)) {
  125. if ($this->appendOnly) {
  126. self::$valuesCache[$file] = $expiresAt;
  127. }
  128. [$expiresAt, $this->values[$id]] = $expiresAt;
  129. } elseif ($now < $expiresAt) {
  130. $this->values[$id] = new LazyValue($file);
  131. }
  132. if ($now >= $expiresAt) {
  133. unset($this->values[$id], $missingIds[$k], self::$valuesCache[$file]);
  134. }
  135. } catch (\ErrorException $e) {
  136. unset($missingIds[$k]);
  137. }
  138. }
  139. } finally {
  140. restore_error_handler();
  141. }
  142. $ids = $missingIds;
  143. $missingIds = [];
  144. }
  145. }
  146. protected function doHave(string $id): bool
  147. {
  148. if ($this->appendOnly && isset($this->values[$id])) {
  149. return true;
  150. }
  151. set_error_handler($this->includeHandler);
  152. try {
  153. $file = $this->files[$id] ??= $this->getFile($id);
  154. $getExpiry = true;
  155. if (isset(self::$valuesCache[$file])) {
  156. [$expiresAt, $value] = self::$valuesCache[$file];
  157. } elseif (\is_array($expiresAt = include $file)) {
  158. if ($this->appendOnly) {
  159. self::$valuesCache[$file] = $expiresAt;
  160. }
  161. [$expiresAt, $value] = $expiresAt;
  162. } elseif ($this->appendOnly) {
  163. $value = new LazyValue($file);
  164. }
  165. } catch (\ErrorException) {
  166. return false;
  167. } finally {
  168. restore_error_handler();
  169. }
  170. if ($this->appendOnly) {
  171. $now = 0;
  172. $this->values[$id] = $value;
  173. } else {
  174. $now = time();
  175. }
  176. return $now < $expiresAt;
  177. }
  178. protected function doSave(array $values, int $lifetime): array|bool
  179. {
  180. $ok = true;
  181. $expiry = $lifetime ? time() + $lifetime : 'PHP_INT_MAX';
  182. $allowCompile = self::isSupported();
  183. foreach ($values as $key => $value) {
  184. unset($this->values[$key]);
  185. $isStaticValue = true;
  186. if (null === $value) {
  187. $value = "'N;'";
  188. } elseif (\is_object($value) || \is_array($value)) {
  189. try {
  190. $value = VarExporter::export($value, $isStaticValue);
  191. } catch (\Exception $e) {
  192. throw new InvalidArgumentException(\sprintf('Cache key "%s" has non-serializable "%s" value.', $key, get_debug_type($value)), 0, $e);
  193. }
  194. } elseif (\is_string($value)) {
  195. // Wrap "N;" in a closure to not confuse it with an encoded `null`
  196. if ('N;' === $value) {
  197. $isStaticValue = false;
  198. }
  199. $value = var_export($value, true);
  200. } elseif (!\is_scalar($value)) {
  201. throw new InvalidArgumentException(\sprintf('Cache key "%s" has non-serializable "%s" value.', $key, get_debug_type($value)));
  202. } else {
  203. $value = var_export($value, true);
  204. }
  205. $encodedKey = rawurlencode($key);
  206. if ($isStaticValue) {
  207. $value = "return [{$expiry}, {$value}];";
  208. } elseif ($this->appendOnly) {
  209. $value = "return [{$expiry}, new class() implements \\".CachedValueInterface::class." { public function getValue(): mixed { return {$value}; } }];";
  210. } else {
  211. // We cannot use a closure here because of https://bugs.php.net/76982
  212. $value = str_replace('\Symfony\Component\VarExporter\Internal\\', '', $value);
  213. $value = "namespace Symfony\Component\VarExporter\Internal;\n\nreturn \$getExpiry ? {$expiry} : {$value};";
  214. }
  215. $file = $this->files[$key] = $this->getFile($key, true);
  216. // Since OPcache only compiles files older than the script execution start, set the file's mtime in the past
  217. $ok = $this->write($file, "<?php //{$encodedKey}\n\n{$value}\n", self::$startTime - 10) && $ok;
  218. if ($allowCompile) {
  219. @opcache_invalidate($file, true);
  220. @opcache_compile_file($file);
  221. }
  222. unset(self::$valuesCache[$file]);
  223. }
  224. if (!$ok && !is_writable($this->directory)) {
  225. throw new CacheException(\sprintf('Cache directory is not writable (%s).', $this->directory));
  226. }
  227. return $ok;
  228. }
  229. protected function doClear(string $namespace): bool
  230. {
  231. $this->values = [];
  232. return $this->doCommonClear($namespace);
  233. }
  234. protected function doDelete(array $ids): bool
  235. {
  236. foreach ($ids as $id) {
  237. unset($this->values[$id]);
  238. }
  239. return $this->doCommonDelete($ids);
  240. }
  241. protected function doUnlink(string $file): bool
  242. {
  243. unset(self::$valuesCache[$file]);
  244. if (self::isSupported()) {
  245. @opcache_invalidate($file, true);
  246. }
  247. return @unlink($file);
  248. }
  249. private function getFileKey(string $file): string
  250. {
  251. if (!$h = @fopen($file, 'r')) {
  252. return '';
  253. }
  254. $encodedKey = substr(fgets($h), 8);
  255. fclose($h);
  256. return rawurldecode(rtrim($encodedKey));
  257. }
  258. }
  259. /**
  260. * @internal
  261. */
  262. class LazyValue
  263. {
  264. public function __construct(
  265. public string $file,
  266. ) {
  267. }
  268. }