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

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