Kernel.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  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.0';
  68. public const VERSION_ID = 70100;
  69. public const MAJOR_VERSION = 7;
  70. public const MINOR_VERSION = 1;
  71. public const RELEASE_VERSION = 0;
  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. $preload = $this instanceof WarmableInterface ? (array) $this->warmUp($this->container->getParameter('kernel.cache_dir'), $buildDir) : [];
  449. if ($this->container->has('cache_warmer')) {
  450. $preload = array_merge($preload, (array) $this->container->get('cache_warmer')->warmUp($this->container->getParameter('kernel.cache_dir'), $buildDir));
  451. }
  452. if ($preload && file_exists($preloadFile = $buildDir.'/'.$class.'.preload.php')) {
  453. Preloader::append($preloadFile, $preload);
  454. }
  455. }
  456. /**
  457. * Returns the kernel parameters.
  458. *
  459. * @return array<string, array|bool|string|int|float|\UnitEnum|null>
  460. */
  461. protected function getKernelParameters(): array
  462. {
  463. $bundles = [];
  464. $bundlesMetadata = [];
  465. foreach ($this->bundles as $name => $bundle) {
  466. $bundles[$name] = $bundle::class;
  467. $bundlesMetadata[$name] = [
  468. 'path' => $bundle->getPath(),
  469. 'namespace' => $bundle->getNamespace(),
  470. ];
  471. }
  472. return [
  473. 'kernel.project_dir' => realpath($this->getProjectDir()) ?: $this->getProjectDir(),
  474. 'kernel.environment' => $this->environment,
  475. 'kernel.runtime_environment' => '%env(default:kernel.environment:APP_RUNTIME_ENV)%',
  476. 'kernel.runtime_mode' => '%env(query_string:default:container.runtime_mode:APP_RUNTIME_MODE)%',
  477. 'kernel.runtime_mode.web' => '%env(bool:default::key:web:default:kernel.runtime_mode:)%',
  478. 'kernel.runtime_mode.cli' => '%env(not:default:kernel.runtime_mode.web:)%',
  479. 'kernel.runtime_mode.worker' => '%env(bool:default::key:worker:default:kernel.runtime_mode:)%',
  480. 'kernel.debug' => $this->debug,
  481. 'kernel.build_dir' => realpath($buildDir = $this->warmupDir ?: $this->getBuildDir()) ?: $buildDir,
  482. 'kernel.cache_dir' => realpath($cacheDir = ($this->getCacheDir() === $this->getBuildDir() ? ($this->warmupDir ?: $this->getCacheDir()) : $this->getCacheDir())) ?: $cacheDir,
  483. 'kernel.logs_dir' => realpath($this->getLogDir()) ?: $this->getLogDir(),
  484. 'kernel.bundles' => $bundles,
  485. 'kernel.bundles_metadata' => $bundlesMetadata,
  486. 'kernel.charset' => $this->getCharset(),
  487. 'kernel.container_class' => $this->getContainerClass(),
  488. ];
  489. }
  490. /**
  491. * Builds the service container.
  492. *
  493. * @throws \RuntimeException
  494. */
  495. protected function buildContainer(): ContainerBuilder
  496. {
  497. foreach (['cache' => $this->getCacheDir(), 'build' => $this->warmupDir ?: $this->getBuildDir(), 'logs' => $this->getLogDir()] as $name => $dir) {
  498. if (!is_dir($dir)) {
  499. if (false === @mkdir($dir, 0777, true) && !is_dir($dir)) {
  500. throw new \RuntimeException(sprintf('Unable to create the "%s" directory (%s).', $name, $dir));
  501. }
  502. } elseif (!is_writable($dir)) {
  503. throw new \RuntimeException(sprintf('Unable to write in the "%s" directory (%s).', $name, $dir));
  504. }
  505. }
  506. $container = $this->getContainerBuilder();
  507. $container->addObjectResource($this);
  508. $this->prepareContainer($container);
  509. $this->registerContainerConfiguration($this->getContainerLoader($container));
  510. return $container;
  511. }
  512. /**
  513. * Prepares the ContainerBuilder before it is compiled.
  514. */
  515. protected function prepareContainer(ContainerBuilder $container): void
  516. {
  517. $extensions = [];
  518. foreach ($this->bundles as $bundle) {
  519. if ($extension = $bundle->getContainerExtension()) {
  520. $container->registerExtension($extension);
  521. }
  522. if ($this->debug) {
  523. $container->addObjectResource($bundle);
  524. }
  525. }
  526. foreach ($this->bundles as $bundle) {
  527. $bundle->build($container);
  528. }
  529. $this->build($container);
  530. foreach ($container->getExtensions() as $extension) {
  531. $extensions[] = $extension->getAlias();
  532. }
  533. // ensure these extensions are implicitly loaded
  534. $container->getCompilerPassConfig()->setMergePass(new MergeExtensionConfigurationPass($extensions));
  535. }
  536. /**
  537. * Gets a new ContainerBuilder instance used to build the service container.
  538. */
  539. protected function getContainerBuilder(): ContainerBuilder
  540. {
  541. $container = new ContainerBuilder();
  542. $container->getParameterBag()->add($this->getKernelParameters());
  543. if ($this instanceof ExtensionInterface) {
  544. $container->registerExtension($this);
  545. }
  546. if ($this instanceof CompilerPassInterface) {
  547. $container->addCompilerPass($this, PassConfig::TYPE_BEFORE_OPTIMIZATION, -10000);
  548. }
  549. return $container;
  550. }
  551. /**
  552. * Dumps the service container to PHP code in the cache.
  553. *
  554. * @param string $class The name of the class to generate
  555. * @param string $baseClass The name of the container's base class
  556. */
  557. protected function dumpContainer(ConfigCache $cache, ContainerBuilder $container, string $class, string $baseClass): void
  558. {
  559. // cache the container
  560. $dumper = new PhpDumper($container);
  561. $buildParameters = [];
  562. foreach ($container->getCompilerPassConfig()->getPasses() as $pass) {
  563. if ($pass instanceof RemoveBuildParametersPass) {
  564. $buildParameters = array_merge($buildParameters, $pass->getRemovedParameters());
  565. }
  566. }
  567. $content = $dumper->dump([
  568. 'class' => $class,
  569. 'base_class' => $baseClass,
  570. 'file' => $cache->getPath(),
  571. 'as_files' => true,
  572. 'debug' => $this->debug,
  573. 'inline_factories' => $buildParameters['.container.dumper.inline_factories'] ?? false,
  574. 'inline_class_loader' => $buildParameters['.container.dumper.inline_class_loader'] ?? $this->debug,
  575. 'build_time' => $container->hasParameter('kernel.container_build_time') ? $container->getParameter('kernel.container_build_time') : time(),
  576. 'preload_classes' => array_map('get_class', $this->bundles),
  577. ]);
  578. $rootCode = array_pop($content);
  579. $dir = \dirname($cache->getPath()).'/';
  580. $fs = new Filesystem();
  581. foreach ($content as $file => $code) {
  582. $fs->dumpFile($dir.$file, $code);
  583. @chmod($dir.$file, 0666 & ~umask());
  584. }
  585. $legacyFile = \dirname($dir.key($content)).'.legacy';
  586. if (is_file($legacyFile)) {
  587. @unlink($legacyFile);
  588. }
  589. $cache->write($rootCode, $container->getResources());
  590. }
  591. /**
  592. * Returns a loader for the container.
  593. */
  594. protected function getContainerLoader(ContainerInterface $container): DelegatingLoader
  595. {
  596. $env = $this->getEnvironment();
  597. $locator = new FileLocator($this);
  598. $resolver = new LoaderResolver([
  599. new XmlFileLoader($container, $locator, $env),
  600. new YamlFileLoader($container, $locator, $env),
  601. new IniFileLoader($container, $locator, $env),
  602. new PhpFileLoader($container, $locator, $env, class_exists(ConfigBuilderGenerator::class) ? new ConfigBuilderGenerator($this->getBuildDir()) : null),
  603. new GlobFileLoader($container, $locator, $env),
  604. new DirectoryLoader($container, $locator, $env),
  605. new ClosureLoader($container, $env),
  606. ]);
  607. return new DelegatingLoader($resolver);
  608. }
  609. private function preBoot(): ContainerInterface
  610. {
  611. if ($this->debug) {
  612. $this->startTime = microtime(true);
  613. }
  614. if ($this->debug && !isset($_ENV['SHELL_VERBOSITY']) && !isset($_SERVER['SHELL_VERBOSITY'])) {
  615. if (\function_exists('putenv')) {
  616. putenv('SHELL_VERBOSITY=3');
  617. }
  618. $_ENV['SHELL_VERBOSITY'] = 3;
  619. $_SERVER['SHELL_VERBOSITY'] = 3;
  620. }
  621. $this->initializeBundles();
  622. $this->initializeContainer();
  623. $container = $this->container;
  624. if ($container->hasParameter('kernel.trusted_hosts') && $trustedHosts = $container->getParameter('kernel.trusted_hosts')) {
  625. Request::setTrustedHosts($trustedHosts);
  626. }
  627. if ($container->hasParameter('kernel.trusted_proxies') && $container->hasParameter('kernel.trusted_headers') && $trustedProxies = $container->getParameter('kernel.trusted_proxies')) {
  628. Request::setTrustedProxies(\is_array($trustedProxies) ? $trustedProxies : array_map('trim', explode(',', $trustedProxies)), $container->getParameter('kernel.trusted_headers'));
  629. }
  630. return $container;
  631. }
  632. public function __sleep(): array
  633. {
  634. return ['environment', 'debug'];
  635. }
  636. public function __wakeup(): void
  637. {
  638. if (\is_object($this->environment) || \is_object($this->debug)) {
  639. throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
  640. }
  641. $this->__construct($this->environment, $this->debug);
  642. }
  643. }