vendor/symfony/http-kernel/Kernel.php line 202

  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\HttpKernel;
  11. use Symfony\Component\Config\Builder\ConfigBuilderGenerator;
  12. use Symfony\Component\Config\ConfigCache;
  13. use Symfony\Component\Config\Loader\DelegatingLoader;
  14. use Symfony\Component\Config\Loader\LoaderResolver;
  15. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  16. use Symfony\Component\DependencyInjection\Compiler\PassConfig;
  17. use Symfony\Component\DependencyInjection\Compiler\RemoveBuildParametersPass;
  18. use Symfony\Component\DependencyInjection\ContainerBuilder;
  19. use Symfony\Component\DependencyInjection\ContainerInterface;
  20. use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
  21. use Symfony\Component\DependencyInjection\Dumper\Preloader;
  22. use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
  23. use Symfony\Component\DependencyInjection\Loader\ClosureLoader;
  24. use Symfony\Component\DependencyInjection\Loader\DirectoryLoader;
  25. use Symfony\Component\DependencyInjection\Loader\GlobFileLoader;
  26. use Symfony\Component\DependencyInjection\Loader\IniFileLoader;
  27. use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
  28. use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
  29. use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
  30. use Symfony\Component\ErrorHandler\DebugClassLoader;
  31. use Symfony\Component\Filesystem\Filesystem;
  32. use Symfony\Component\HttpFoundation\Request;
  33. use Symfony\Component\HttpFoundation\Response;
  34. use Symfony\Component\HttpKernel\Bundle\BundleInterface;
  35. use Symfony\Component\HttpKernel\CacheWarmer\WarmableInterface;
  36. use Symfony\Component\HttpKernel\Config\FileLocator;
  37. use Symfony\Component\HttpKernel\DependencyInjection\AddAnnotatedClassesToCachePass;
  38. use Symfony\Component\HttpKernel\DependencyInjection\MergeExtensionConfigurationPass;
  39. // Help opcache.preload discover always-needed symbols
  40. class_exists(ConfigCache::class);
  41. /**
  42. * The Kernel is the heart of the Symfony system.
  43. *
  44. * It manages an environment made of bundles.
  45. *
  46. * Environment names must always start with a letter and
  47. * they must only contain letters and numbers.
  48. *
  49. * @author Fabien Potencier <fabien@symfony.com>
  50. */
  51. abstract class Kernel implements KernelInterface, RebootableInterface, TerminableInterface
  52. {
  53. /**
  54. * @var array<string, BundleInterface>
  55. */
  56. protected $bundles = [];
  57. protected $container;
  58. protected $environment;
  59. protected $debug;
  60. protected $booted = false;
  61. protected $startTime;
  62. private string $projectDir;
  63. private ?string $warmupDir = null;
  64. private int $requestStackSize = 0;
  65. private bool $resetServices = false;
  66. private bool $handlingHttpCache = false;
  67. /**
  68. * @var array<string, bool>
  69. */
  70. private static array $freshCache = [];
  71. public const VERSION = '6.4.36';
  72. public const VERSION_ID = 60436;
  73. public const MAJOR_VERSION = 6;
  74. public const MINOR_VERSION = 4;
  75. public const RELEASE_VERSION = 36;
  76. public const EXTRA_VERSION = '';
  77. public const END_OF_MAINTENANCE = '11/2026';
  78. public const END_OF_LIFE = '11/2027';
  79. public function __construct(string $environment, bool $debug)
  80. {
  81. if (!$this->environment = $environment) {
  82. throw new \InvalidArgumentException(\sprintf('Invalid environment provided to "%s": the environment cannot be empty.', get_debug_type($this)));
  83. }
  84. $this->debug = $debug;
  85. }
  86. public function __clone()
  87. {
  88. $this->booted = false;
  89. $this->container = null;
  90. $this->requestStackSize = 0;
  91. $this->resetServices = false;
  92. $this->handlingHttpCache = false;
  93. }
  94. /**
  95. * @return void
  96. */
  97. public function boot()
  98. {
  99. if ($this->booted) {
  100. if (!$this->requestStackSize && $this->resetServices) {
  101. if ($this->container->has('services_resetter')) {
  102. $this->container->get('services_resetter')->reset();
  103. }
  104. $this->resetServices = false;
  105. if ($this->debug) {
  106. $this->startTime = microtime(true);
  107. }
  108. }
  109. return;
  110. }
  111. if (!$this->container) {
  112. $this->preBoot();
  113. }
  114. foreach ($this->getBundles() as $bundle) {
  115. $bundle->setContainer($this->container);
  116. $bundle->boot();
  117. }
  118. $this->booted = true;
  119. }
  120. /**
  121. * @return void
  122. */
  123. public function reboot(?string $warmupDir)
  124. {
  125. $this->shutdown();
  126. $this->warmupDir = $warmupDir;
  127. $this->boot();
  128. }
  129. /**
  130. * @return void
  131. */
  132. public function terminate(Request $request, Response $response)
  133. {
  134. if (!$this->booted) {
  135. return;
  136. }
  137. if ($this->getHttpKernel() instanceof TerminableInterface) {
  138. $this->getHttpKernel()->terminate($request, $response);
  139. }
  140. }
  141. /**
  142. * @return void
  143. */
  144. public function shutdown()
  145. {
  146. if (!$this->booted) {
  147. return;
  148. }
  149. $this->booted = false;
  150. foreach ($this->getBundles() as $bundle) {
  151. $bundle->shutdown();
  152. $bundle->setContainer(null);
  153. }
  154. $this->container = null;
  155. $this->requestStackSize = 0;
  156. $this->resetServices = false;
  157. }
  158. public function handle(Request $request, int $type = HttpKernelInterface::MAIN_REQUEST, bool $catch = true): Response
  159. {
  160. if (!$this->container) {
  161. $this->preBoot();
  162. }
  163. if (HttpKernelInterface::MAIN_REQUEST === $type && !$this->handlingHttpCache && $this->container->has('http_cache')) {
  164. $this->handlingHttpCache = true;
  165. try {
  166. return $this->container->get('http_cache')->handle($request, $type, $catch);
  167. } finally {
  168. $this->handlingHttpCache = false;
  169. $this->resetServices = true;
  170. }
  171. }
  172. $this->boot();
  173. ++$this->requestStackSize;
  174. if (!$this->handlingHttpCache) {
  175. $this->resetServices = true;
  176. }
  177. try {
  178. return $this->getHttpKernel()->handle($request, $type, $catch);
  179. } finally {
  180. --$this->requestStackSize;
  181. }
  182. }
  183. /**
  184. * Gets an HTTP kernel from the container.
  185. */
  186. protected function getHttpKernel(): HttpKernelInterface
  187. {
  188. return $this->container->get('http_kernel');
  189. }
  190. public function getBundles(): array
  191. {
  192. return $this->bundles;
  193. }
  194. public function getBundle(string $name): BundleInterface
  195. {
  196. if (!isset($this->bundles[$name])) {
  197. throw new \InvalidArgumentException(\sprintf('Bundle "%s" does not exist or it is not enabled. Maybe you forgot to add it in the "registerBundles()" method of your "%s.php" file?', $name, get_debug_type($this)));
  198. }
  199. return $this->bundles[$name];
  200. }
  201. public function locateResource(string $name): string
  202. {
  203. if ('@' !== $name[0]) {
  204. throw new \InvalidArgumentException(\sprintf('A resource name must start with @ ("%s" given).', $name));
  205. }
  206. if (str_contains($name, '..')) {
  207. throw new \RuntimeException(\sprintf('File name "%s" contains invalid characters (..).', $name));
  208. }
  209. $bundleName = substr($name, 1);
  210. $path = '';
  211. if (str_contains($bundleName, '/')) {
  212. [$bundleName, $path] = explode('/', $bundleName, 2);
  213. }
  214. $bundle = $this->getBundle($bundleName);
  215. if (file_exists($file = $bundle->getPath().'/'.$path)) {
  216. return $file;
  217. }
  218. throw new \InvalidArgumentException(\sprintf('Unable to find file "%s".', $name));
  219. }
  220. public function getEnvironment(): string
  221. {
  222. return $this->environment;
  223. }
  224. public function isDebug(): bool
  225. {
  226. return $this->debug;
  227. }
  228. /**
  229. * Gets the application root dir (path of the project's composer file).
  230. */
  231. public function getProjectDir(): string
  232. {
  233. if (!isset($this->projectDir)) {
  234. $r = new \ReflectionObject($this);
  235. if (!is_file($dir = $r->getFileName())) {
  236. throw new \LogicException(\sprintf('Cannot auto-detect project dir for kernel of class "%s".', $r->name));
  237. }
  238. $dir = $rootDir = \dirname($dir);
  239. while (!is_file($dir.'/composer.json')) {
  240. if ($dir === \dirname($dir)) {
  241. return $this->projectDir = $rootDir;
  242. }
  243. $dir = \dirname($dir);
  244. }
  245. $this->projectDir = $dir;
  246. }
  247. return $this->projectDir;
  248. }
  249. public function getContainer(): ContainerInterface
  250. {
  251. if (!$this->container) {
  252. throw new \LogicException('Cannot retrieve the container from a non-booted kernel.');
  253. }
  254. return $this->container;
  255. }
  256. /**
  257. * @internal
  258. */
  259. public function setAnnotatedClassCache(array $annotatedClasses): void
  260. {
  261. file_put_contents(($this->warmupDir ?: $this->getBuildDir()).'/annotations.map', \sprintf('<?php return %s;', var_export($annotatedClasses, true)));
  262. }
  263. public function getStartTime(): float
  264. {
  265. return $this->debug && null !== $this->startTime ? $this->startTime : -\INF;
  266. }
  267. public function getCacheDir(): string
  268. {
  269. return $this->getProjectDir().'/var/cache/'.$this->environment;
  270. }
  271. public function getBuildDir(): string
  272. {
  273. // Returns $this->getCacheDir() for backward compatibility
  274. return $this->getCacheDir();
  275. }
  276. public function getLogDir(): string
  277. {
  278. return $this->getProjectDir().'/var/log';
  279. }
  280. public function getCharset(): string
  281. {
  282. return 'UTF-8';
  283. }
  284. /**
  285. * Gets the patterns defining the classes to parse and cache for annotations.
  286. */
  287. public function getAnnotatedClassesToCompile(): array
  288. {
  289. return [];
  290. }
  291. /**
  292. * Initializes bundles.
  293. *
  294. * @return void
  295. *
  296. * @throws \LogicException if two bundles share a common name
  297. */
  298. protected function initializeBundles()
  299. {
  300. // init bundles
  301. $this->bundles = [];
  302. foreach ($this->registerBundles() as $bundle) {
  303. $name = $bundle->getName();
  304. if (isset($this->bundles[$name])) {
  305. throw new \LogicException(\sprintf('Trying to register two bundles with the same name "%s".', $name));
  306. }
  307. $this->bundles[$name] = $bundle;
  308. }
  309. }
  310. /**
  311. * The extension point similar to the Bundle::build() method.
  312. *
  313. * Use this method to register compiler passes and manipulate the container during the building process.
  314. *
  315. * @return void
  316. */
  317. protected function build(ContainerBuilder $container)
  318. {
  319. }
  320. /**
  321. * Gets the container class.
  322. *
  323. * @throws \InvalidArgumentException If the generated classname is invalid
  324. */
  325. protected function getContainerClass(): string
  326. {
  327. $class = static::class;
  328. $class = str_contains($class, "@anonymous\0") ? get_parent_class($class).str_replace('.', '_', ContainerBuilder::hash($class)) : $class;
  329. $class = str_replace('\\', '_', $class).ucfirst($this->environment).($this->debug ? 'Debug' : '').'Container';
  330. if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $class)) {
  331. throw new \InvalidArgumentException(\sprintf('The environment "%s" contains invalid characters, it can only contain characters allowed in PHP class names.', $this->environment));
  332. }
  333. return $class;
  334. }
  335. /**
  336. * Gets the container's base class.
  337. *
  338. * All names except Container must be fully qualified.
  339. */
  340. protected function getContainerBaseClass(): string
  341. {
  342. return 'Container';
  343. }
  344. /**
  345. * Initializes the service container.
  346. *
  347. * The built version of the service container is used when fresh, otherwise the
  348. * container is built.
  349. *
  350. * @return void
  351. */
  352. protected function initializeContainer()
  353. {
  354. $class = $this->getContainerClass();
  355. $buildDir = $this->warmupDir ?: $this->getBuildDir();
  356. $cache = new ConfigCache($buildDir.'/'.$class.'.php', $this->debug);
  357. $cachePath = $cache->getPath();
  358. // Silence E_WARNING to ignore "include" failures - don't use "@" to prevent silencing fatal errors
  359. $errorLevel = error_reporting();
  360. error_reporting($errorLevel & ~\E_WARNING);
  361. try {
  362. if (is_file($cachePath) && \is_object($this->container = include $cachePath)
  363. && (!$this->debug || (self::$freshCache[$cachePath] ?? $cache->isFresh()))
  364. ) {
  365. self::$freshCache[$cachePath] = true;
  366. $this->container->set('kernel', $this);
  367. error_reporting($errorLevel);
  368. return;
  369. }
  370. } catch (\Throwable $e) {
  371. }
  372. $oldContainer = \is_object($this->container) ? new \ReflectionClass($this->container) : $this->container = null;
  373. try {
  374. is_dir($buildDir) ?: mkdir($buildDir, 0777, true);
  375. if ($lock = fopen($cachePath.'.lock', 'w+')) {
  376. if (!flock($lock, \LOCK_EX | \LOCK_NB, $wouldBlock) && !flock($lock, $wouldBlock ? \LOCK_SH : \LOCK_EX)) {
  377. fclose($lock);
  378. $lock = null;
  379. } elseif (!is_file($cachePath) || !\is_object($this->container = include $cachePath)) {
  380. $this->container = null;
  381. } elseif (!$oldContainer || $this->container::class !== $oldContainer->name) {
  382. flock($lock, \LOCK_UN);
  383. fclose($lock);
  384. $this->container->set('kernel', $this);
  385. return;
  386. }
  387. }
  388. } catch (\Throwable $e) {
  389. } finally {
  390. error_reporting($errorLevel);
  391. }
  392. if ($collectDeprecations = $this->debug && !\defined('PHPUNIT_COMPOSER_INSTALL')) {
  393. $collectedLogs = [];
  394. $previousHandler = set_error_handler(function ($type, $message, $file, $line) use (&$collectedLogs, &$previousHandler) {
  395. if (\E_USER_DEPRECATED !== $type && \E_DEPRECATED !== $type) {
  396. return $previousHandler ? $previousHandler($type, $message, $file, $line) : false;
  397. }
  398. if (isset($collectedLogs[$message])) {
  399. ++$collectedLogs[$message]['count'];
  400. return null;
  401. }
  402. $backtrace = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 5);
  403. // Clean the trace by removing first frames added by the error handler itself.
  404. for ($i = 0; isset($backtrace[$i]); ++$i) {
  405. if (isset($backtrace[$i]['file'], $backtrace[$i]['line']) && $backtrace[$i]['line'] === $line && $backtrace[$i]['file'] === $file) {
  406. $backtrace = \array_slice($backtrace, 1 + $i);
  407. break;
  408. }
  409. }
  410. for ($i = 0; isset($backtrace[$i]); ++$i) {
  411. if (!isset($backtrace[$i]['file'], $backtrace[$i]['line'], $backtrace[$i]['function'])) {
  412. continue;
  413. }
  414. if (!isset($backtrace[$i]['class']) && 'trigger_deprecation' === $backtrace[$i]['function']) {
  415. $file = $backtrace[$i]['file'];
  416. $line = $backtrace[$i]['line'];
  417. $backtrace = \array_slice($backtrace, 1 + $i);
  418. break;
  419. }
  420. }
  421. // Remove frames added by DebugClassLoader.
  422. for ($i = \count($backtrace) - 2; 0 < $i; --$i) {
  423. if (DebugClassLoader::class === ($backtrace[$i]['class'] ?? null)) {
  424. $backtrace = [$backtrace[$i + 1]];
  425. break;
  426. }
  427. }
  428. $collectedLogs[$message] = [
  429. 'type' => $type,
  430. 'message' => $message,
  431. 'file' => $file,
  432. 'line' => $line,
  433. 'trace' => [$backtrace[0]],
  434. 'count' => 1,
  435. ];
  436. return null;
  437. });
  438. }
  439. try {
  440. $container = null;
  441. $container = $this->buildContainer();
  442. $container->compile();
  443. } finally {
  444. if ($collectDeprecations) {
  445. restore_error_handler();
  446. @file_put_contents($buildDir.'/'.$class.'Deprecations.log', serialize(array_values($collectedLogs)));
  447. @file_put_contents($buildDir.'/'.$class.'Compiler.log', null !== $container ? implode("\n", $container->getCompiler()->getLog()) : '');
  448. }
  449. }
  450. $this->dumpContainer($cache, $container, $class, $this->getContainerBaseClass());
  451. if ($lock) {
  452. flock($lock, \LOCK_UN);
  453. fclose($lock);
  454. }
  455. $this->container = require $cachePath;
  456. $this->container->set('kernel', $this);
  457. if ($oldContainer && $this->container::class !== $oldContainer->name) {
  458. // Because concurrent requests might still be using them,
  459. // old container files are not removed immediately,
  460. // but on a next dump of the container.
  461. static $legacyContainers = [];
  462. $oldContainerDir = \dirname($oldContainer->getFileName());
  463. $legacyContainers[$oldContainerDir.'.legacy'] = true;
  464. foreach (glob(\dirname($oldContainerDir).\DIRECTORY_SEPARATOR.'*.legacy', \GLOB_NOSORT) as $legacyContainer) {
  465. if (!isset($legacyContainers[$legacyContainer]) && @unlink($legacyContainer)) {
  466. (new Filesystem())->remove(substr($legacyContainer, 0, -7));
  467. }
  468. }
  469. touch($oldContainerDir.'.legacy');
  470. }
  471. $buildDir = $this->container->getParameter('kernel.build_dir');
  472. $cacheDir = $this->container->getParameter('kernel.cache_dir');
  473. $preload = $this instanceof WarmableInterface ? (array) $this->warmUp($cacheDir, $buildDir) : [];
  474. if ($this->container->has('cache_warmer')) {
  475. $cacheWarmer = $this->container->get('cache_warmer');
  476. if ($cacheDir !== $buildDir) {
  477. $cacheWarmer->enableOptionalWarmers();
  478. }
  479. $preload = array_merge($preload, (array) $cacheWarmer->warmUp($cacheDir, $buildDir));
  480. }
  481. if ($preload && file_exists($preloadFile = $buildDir.'/'.$class.'.preload.php')) {
  482. Preloader::append($preloadFile, $preload);
  483. }
  484. }
  485. /**
  486. * Returns the kernel parameters.
  487. */
  488. protected function getKernelParameters(): array
  489. {
  490. $bundles = [];
  491. $bundlesMetadata = [];
  492. foreach ($this->bundles as $name => $bundle) {
  493. $bundles[$name] = $bundle::class;
  494. $bundlesMetadata[$name] = [
  495. 'path' => $bundle->getPath(),
  496. 'namespace' => $bundle->getNamespace(),
  497. ];
  498. }
  499. return [
  500. 'kernel.project_dir' => realpath($this->getProjectDir()) ?: $this->getProjectDir(),
  501. 'kernel.environment' => $this->environment,
  502. 'kernel.runtime_environment' => '%env(default:kernel.environment:APP_RUNTIME_ENV)%',
  503. 'kernel.runtime_mode' => '%env(query_string:default:container.runtime_mode:APP_RUNTIME_MODE)%',
  504. 'kernel.runtime_mode.web' => '%env(bool:default::key:web:default:kernel.runtime_mode:)%',
  505. 'kernel.runtime_mode.cli' => '%env(not:default:kernel.runtime_mode.web:)%',
  506. 'kernel.runtime_mode.worker' => '%env(bool:default::key:worker:default:kernel.runtime_mode:)%',
  507. 'kernel.debug' => $this->debug,
  508. 'kernel.build_dir' => realpath($buildDir = $this->warmupDir ?: $this->getBuildDir()) ?: $buildDir,
  509. 'kernel.cache_dir' => realpath($cacheDir = ($this->getCacheDir() === $this->getBuildDir() ? ($this->warmupDir ?: $this->getCacheDir()) : $this->getCacheDir())) ?: $cacheDir,
  510. 'kernel.logs_dir' => realpath($this->getLogDir()) ?: $this->getLogDir(),
  511. 'kernel.bundles' => $bundles,
  512. 'kernel.bundles_metadata' => $bundlesMetadata,
  513. 'kernel.charset' => $this->getCharset(),
  514. 'kernel.container_class' => $this->getContainerClass(),
  515. ];
  516. }
  517. /**
  518. * Builds the service container.
  519. *
  520. * @throws \RuntimeException
  521. */
  522. protected function buildContainer(): ContainerBuilder
  523. {
  524. foreach (['cache' => $this->getCacheDir(), 'build' => $this->warmupDir ?: $this->getBuildDir(), 'logs' => $this->getLogDir()] as $name => $dir) {
  525. if (!is_dir($dir)) {
  526. if (!@mkdir($dir, 0o777, true) && !is_dir($dir)) {
  527. throw new \RuntimeException(\sprintf('Unable to create the "%s" directory (%s).', $name, $dir));
  528. }
  529. } elseif (!is_writable($dir)) {
  530. throw new \RuntimeException(\sprintf('Unable to write in the "%s" directory (%s).', $name, $dir));
  531. }
  532. }
  533. $container = $this->getContainerBuilder();
  534. $container->addObjectResource($this);
  535. $this->prepareContainer($container);
  536. $this->registerContainerConfiguration($this->getContainerLoader($container));
  537. $container->addCompilerPass(new AddAnnotatedClassesToCachePass($this));
  538. return $container;
  539. }
  540. /**
  541. * Prepares the ContainerBuilder before it is compiled.
  542. *
  543. * @return void
  544. */
  545. protected function prepareContainer(ContainerBuilder $container)
  546. {
  547. $extensions = [];
  548. foreach ($this->bundles as $bundle) {
  549. if ($extension = $bundle->getContainerExtension()) {
  550. $container->registerExtension($extension);
  551. }
  552. if ($this->debug) {
  553. $container->addObjectResource($bundle);
  554. }
  555. }
  556. foreach ($this->bundles as $bundle) {
  557. $bundle->build($container);
  558. }
  559. $this->build($container);
  560. foreach ($container->getExtensions() as $extension) {
  561. $extensions[] = $extension->getAlias();
  562. }
  563. // ensure these extensions are implicitly loaded
  564. $container->getCompilerPassConfig()->setMergePass(new MergeExtensionConfigurationPass($extensions));
  565. }
  566. /**
  567. * Gets a new ContainerBuilder instance used to build the service container.
  568. */
  569. protected function getContainerBuilder(): ContainerBuilder
  570. {
  571. $container = new ContainerBuilder();
  572. $container->getParameterBag()->add($this->getKernelParameters());
  573. if ($this instanceof ExtensionInterface) {
  574. $container->registerExtension($this);
  575. }
  576. if ($this instanceof CompilerPassInterface) {
  577. $container->addCompilerPass($this, PassConfig::TYPE_BEFORE_OPTIMIZATION, -10000);
  578. }
  579. return $container;
  580. }
  581. /**
  582. * Dumps the service container to PHP code in the cache.
  583. *
  584. * @param string $class The name of the class to generate
  585. * @param string $baseClass The name of the container's base class
  586. *
  587. * @return void
  588. */
  589. protected function dumpContainer(ConfigCache $cache, ContainerBuilder $container, string $class, string $baseClass)
  590. {
  591. // cache the container
  592. $dumper = new PhpDumper($container);
  593. $buildParameters = [];
  594. foreach ($container->getCompilerPassConfig()->getPasses() as $pass) {
  595. if ($pass instanceof RemoveBuildParametersPass) {
  596. $buildParameters = array_merge($buildParameters, $pass->getRemovedParameters());
  597. }
  598. }
  599. $inlineFactories = false;
  600. if (isset($buildParameters['.container.dumper.inline_factories'])) {
  601. $inlineFactories = $buildParameters['.container.dumper.inline_factories'];
  602. } elseif ($container->hasParameter('container.dumper.inline_factories')) {
  603. trigger_deprecation('symfony/http-kernel', '6.3', 'Parameter "%s" is deprecated, use ".%1$s" instead.', 'container.dumper.inline_factories');
  604. $inlineFactories = $container->getParameter('container.dumper.inline_factories');
  605. }
  606. $inlineClassLoader = $this->debug;
  607. if (isset($buildParameters['.container.dumper.inline_class_loader'])) {
  608. $inlineClassLoader = $buildParameters['.container.dumper.inline_class_loader'];
  609. } elseif ($container->hasParameter('container.dumper.inline_class_loader')) {
  610. trigger_deprecation('symfony/http-kernel', '6.3', 'Parameter "%s" is deprecated, use ".%1$s" instead.', 'container.dumper.inline_class_loader');
  611. $inlineClassLoader = $container->getParameter('container.dumper.inline_class_loader');
  612. }
  613. $content = $dumper->dump([
  614. 'class' => $class,
  615. 'base_class' => $baseClass,
  616. 'file' => $cache->getPath(),
  617. 'as_files' => true,
  618. 'debug' => $this->debug,
  619. 'inline_factories' => $inlineFactories,
  620. 'inline_class_loader' => $inlineClassLoader,
  621. 'build_time' => $container->hasParameter('kernel.container_build_time') ? $container->getParameter('kernel.container_build_time') : time(),
  622. 'preload_classes' => array_map('get_class', $this->bundles),
  623. ]);
  624. $rootCode = array_pop($content);
  625. $dir = \dirname($cache->getPath()).'/';
  626. $fs = new Filesystem();
  627. foreach ($content as $file => $code) {
  628. $fs->dumpFile($dir.$file, $code);
  629. @chmod($dir.$file, 0666 & ~umask());
  630. }
  631. $legacyFile = \dirname($dir.key($content)).'.legacy';
  632. if (is_file($legacyFile)) {
  633. @unlink($legacyFile);
  634. }
  635. $cache->write($rootCode, $container->getResources());
  636. }
  637. /**
  638. * Returns a loader for the container.
  639. */
  640. protected function getContainerLoader(ContainerInterface $container): DelegatingLoader
  641. {
  642. $env = $this->getEnvironment();
  643. $locator = new FileLocator($this);
  644. $resolver = new LoaderResolver([
  645. new XmlFileLoader($container, $locator, $env),
  646. new YamlFileLoader($container, $locator, $env),
  647. new IniFileLoader($container, $locator, $env),
  648. new PhpFileLoader($container, $locator, $env, class_exists(ConfigBuilderGenerator::class) ? new ConfigBuilderGenerator($this->getBuildDir()) : null),
  649. new GlobFileLoader($container, $locator, $env),
  650. new DirectoryLoader($container, $locator, $env),
  651. new ClosureLoader($container, $env),
  652. ]);
  653. return new DelegatingLoader($resolver);
  654. }
  655. private function preBoot(): ContainerInterface
  656. {
  657. if ($this->debug) {
  658. $this->startTime = microtime(true);
  659. }
  660. if ($this->debug && !isset($_ENV['SHELL_VERBOSITY']) && !isset($_SERVER['SHELL_VERBOSITY'])) {
  661. if (\function_exists('putenv')) {
  662. putenv('SHELL_VERBOSITY=3');
  663. }
  664. $_ENV['SHELL_VERBOSITY'] = 3;
  665. $_SERVER['SHELL_VERBOSITY'] = 3;
  666. }
  667. $this->initializeBundles();
  668. $this->initializeContainer();
  669. $container = $this->container;
  670. if ($container->hasParameter('kernel.trusted_hosts') && $trustedHosts = $container->getParameter('kernel.trusted_hosts')) {
  671. Request::setTrustedHosts($trustedHosts);
  672. }
  673. if ($container->hasParameter('kernel.trusted_proxies') && $container->hasParameter('kernel.trusted_headers') && $trustedProxies = $container->getParameter('kernel.trusted_proxies')) {
  674. Request::setTrustedProxies(\is_array($trustedProxies) ? $trustedProxies : array_map('trim', explode(',', $trustedProxies)), $container->getParameter('kernel.trusted_headers'));
  675. }
  676. return $container;
  677. }
  678. /**
  679. * Removes comments from a PHP source string.
  680. *
  681. * We don't use the PHP php_strip_whitespace() function
  682. * as we want the content to be readable and well-formatted.
  683. *
  684. * @deprecated since Symfony 6.4 without replacement
  685. */
  686. public static function stripComments(string $source): string
  687. {
  688. trigger_deprecation('symfony/http-kernel', '6.4', 'Method "%s()" is deprecated without replacement.', __METHOD__);
  689. if (!\function_exists('token_get_all')) {
  690. return $source;
  691. }
  692. $rawChunk = '';
  693. $output = '';
  694. $tokens = token_get_all($source);
  695. $ignoreSpace = false;
  696. for ($i = 0; isset($tokens[$i]); ++$i) {
  697. $token = $tokens[$i];
  698. if (!isset($token[1]) || 'b"' === $token) {
  699. $rawChunk .= $token;
  700. } elseif (\T_START_HEREDOC === $token[0]) {
  701. $output .= $rawChunk.$token[1];
  702. do {
  703. $token = $tokens[++$i];
  704. $output .= isset($token[1]) && 'b"' !== $token ? $token[1] : $token;
  705. } while (\T_END_HEREDOC !== $token[0]);
  706. $rawChunk = '';
  707. } elseif (\T_WHITESPACE === $token[0]) {
  708. if ($ignoreSpace) {
  709. $ignoreSpace = false;
  710. continue;
  711. }
  712. // replace multiple new lines with a single newline
  713. $rawChunk .= preg_replace(['/\n{2,}/S'], "\n", $token[1]);
  714. } elseif (\in_array($token[0], [\T_COMMENT, \T_DOC_COMMENT])) {
  715. if (!\in_array($rawChunk[\strlen($rawChunk) - 1], [' ', "\n", "\r", "\t"], true)) {
  716. $rawChunk .= ' ';
  717. }
  718. $ignoreSpace = true;
  719. } else {
  720. $rawChunk .= $token[1];
  721. // The PHP-open tag already has a new-line
  722. if (\T_OPEN_TAG === $token[0]) {
  723. $ignoreSpace = true;
  724. } else {
  725. $ignoreSpace = false;
  726. }
  727. }
  728. }
  729. $output .= $rawChunk;
  730. unset($tokens, $rawChunk);
  731. gc_mem_caches();
  732. return $output;
  733. }
  734. public function __sleep(): array
  735. {
  736. return ['environment', 'debug'];
  737. }
  738. /**
  739. * @return void
  740. */
  741. public function __wakeup()
  742. {
  743. if (\is_object($this->environment) || \is_object($this->debug)) {
  744. throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
  745. }
  746. $this->__construct($this->environment, $this->debug);
  747. }
  748. }