Kernel.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  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.2.6';
  68. public const VERSION_ID = 70206;
  69. public const MAJOR_VERSION = 7;
  70. public const MINOR_VERSION = 2;
  71. public const RELEASE_VERSION = 6;
  72. public const EXTRA_VERSION = '';
  73. public const END_OF_MAINTENANCE = '07/2025';
  74. public const END_OF_LIFE = '07/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. $skip = $_SERVER['SYMFONY_DISABLE_RESOURCE_TRACKING'] ?? '';
  335. $skip = filter_var($skip, \FILTER_VALIDATE_BOOLEAN, \FILTER_NULL_ON_FAILURE) ?? explode(',', $skip);
  336. $cache = new ConfigCache($buildDir.'/'.$class.'.php', $this->debug, null, \is_array($skip) && ['*'] !== $skip ? $skip : ($skip ? [] : null));
  337. $cachePath = $cache->getPath();
  338. // Silence E_WARNING to ignore "include" failures - don't use "@" to prevent silencing fatal errors
  339. $errorLevel = error_reporting();
  340. error_reporting($errorLevel & ~\E_WARNING);
  341. try {
  342. if (is_file($cachePath) && \is_object($this->container = include $cachePath)
  343. && (!$this->debug || (self::$freshCache[$cachePath] ?? $cache->isFresh()))
  344. ) {
  345. self::$freshCache[$cachePath] = true;
  346. $this->container->set('kernel', $this);
  347. error_reporting($errorLevel);
  348. return;
  349. }
  350. } catch (\Throwable $e) {
  351. }
  352. $oldContainer = \is_object($this->container) ? new \ReflectionClass($this->container) : $this->container = null;
  353. try {
  354. is_dir($buildDir) ?: mkdir($buildDir, 0777, true);
  355. if ($lock = fopen($cachePath.'.lock', 'w+')) {
  356. if (!flock($lock, \LOCK_EX | \LOCK_NB, $wouldBlock) && !flock($lock, $wouldBlock ? \LOCK_SH : \LOCK_EX)) {
  357. fclose($lock);
  358. $lock = null;
  359. } elseif (!is_file($cachePath) || !\is_object($this->container = include $cachePath)) {
  360. $this->container = null;
  361. } elseif (!$oldContainer || $this->container::class !== $oldContainer->name) {
  362. flock($lock, \LOCK_UN);
  363. fclose($lock);
  364. $this->container->set('kernel', $this);
  365. return;
  366. }
  367. }
  368. } catch (\Throwable $e) {
  369. } finally {
  370. error_reporting($errorLevel);
  371. }
  372. if ($collectDeprecations = $this->debug && !\defined('PHPUNIT_COMPOSER_INSTALL')) {
  373. $collectedLogs = [];
  374. $previousHandler = set_error_handler(function ($type, $message, $file, $line) use (&$collectedLogs, &$previousHandler) {
  375. if (\E_USER_DEPRECATED !== $type && \E_DEPRECATED !== $type) {
  376. return $previousHandler ? $previousHandler($type, $message, $file, $line) : false;
  377. }
  378. if (isset($collectedLogs[$message])) {
  379. ++$collectedLogs[$message]['count'];
  380. return null;
  381. }
  382. $backtrace = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 5);
  383. // Clean the trace by removing first frames added by the error handler itself.
  384. for ($i = 0; isset($backtrace[$i]); ++$i) {
  385. if (isset($backtrace[$i]['file'], $backtrace[$i]['line']) && $backtrace[$i]['line'] === $line && $backtrace[$i]['file'] === $file) {
  386. $backtrace = \array_slice($backtrace, 1 + $i);
  387. break;
  388. }
  389. }
  390. for ($i = 0; isset($backtrace[$i]); ++$i) {
  391. if (!isset($backtrace[$i]['file'], $backtrace[$i]['line'], $backtrace[$i]['function'])) {
  392. continue;
  393. }
  394. if (!isset($backtrace[$i]['class']) && 'trigger_deprecation' === $backtrace[$i]['function']) {
  395. $file = $backtrace[$i]['file'];
  396. $line = $backtrace[$i]['line'];
  397. $backtrace = \array_slice($backtrace, 1 + $i);
  398. break;
  399. }
  400. }
  401. // Remove frames added by DebugClassLoader.
  402. for ($i = \count($backtrace) - 2; 0 < $i; --$i) {
  403. if (DebugClassLoader::class === ($backtrace[$i]['class'] ?? null)) {
  404. $backtrace = [$backtrace[$i + 1]];
  405. break;
  406. }
  407. }
  408. $collectedLogs[$message] = [
  409. 'type' => $type,
  410. 'message' => $message,
  411. 'file' => $file,
  412. 'line' => $line,
  413. 'trace' => [$backtrace[0]],
  414. 'count' => 1,
  415. ];
  416. return null;
  417. });
  418. }
  419. try {
  420. $container = null;
  421. $container = $this->buildContainer();
  422. $container->compile();
  423. } finally {
  424. if ($collectDeprecations) {
  425. restore_error_handler();
  426. @file_put_contents($buildDir.'/'.$class.'Deprecations.log', serialize(array_values($collectedLogs)));
  427. @file_put_contents($buildDir.'/'.$class.'Compiler.log', null !== $container ? implode("\n", $container->getCompiler()->getLog()) : '');
  428. }
  429. }
  430. $this->dumpContainer($cache, $container, $class, $this->getContainerBaseClass());
  431. if ($lock) {
  432. flock($lock, \LOCK_UN);
  433. fclose($lock);
  434. }
  435. $this->container = require $cachePath;
  436. $this->container->set('kernel', $this);
  437. if ($oldContainer && $this->container::class !== $oldContainer->name) {
  438. // Because concurrent requests might still be using them,
  439. // old container files are not removed immediately,
  440. // but on a next dump of the container.
  441. static $legacyContainers = [];
  442. $oldContainerDir = \dirname($oldContainer->getFileName());
  443. $legacyContainers[$oldContainerDir.'.legacy'] = true;
  444. foreach (glob(\dirname($oldContainerDir).\DIRECTORY_SEPARATOR.'*.legacy', \GLOB_NOSORT) as $legacyContainer) {
  445. if (!isset($legacyContainers[$legacyContainer]) && @unlink($legacyContainer)) {
  446. (new Filesystem())->remove(substr($legacyContainer, 0, -7));
  447. }
  448. }
  449. touch($oldContainerDir.'.legacy');
  450. }
  451. $buildDir = $this->container->getParameter('kernel.build_dir');
  452. $cacheDir = $this->container->getParameter('kernel.cache_dir');
  453. $preload = $this instanceof WarmableInterface ? $this->warmUp($cacheDir, $buildDir) : [];
  454. if ($this->container->has('cache_warmer')) {
  455. $cacheWarmer = $this->container->get('cache_warmer');
  456. if ($cacheDir !== $buildDir) {
  457. $cacheWarmer->enableOptionalWarmers();
  458. }
  459. $preload = array_merge($preload, $cacheWarmer->warmUp($cacheDir, $buildDir));
  460. }
  461. if ($preload && file_exists($preloadFile = $buildDir.'/'.$class.'.preload.php')) {
  462. Preloader::append($preloadFile, $preload);
  463. }
  464. }
  465. /**
  466. * Returns the kernel parameters.
  467. *
  468. * @return array<string, array|bool|string|int|float|\UnitEnum|null>
  469. */
  470. protected function getKernelParameters(): array
  471. {
  472. $bundles = [];
  473. $bundlesMetadata = [];
  474. foreach ($this->bundles as $name => $bundle) {
  475. $bundles[$name] = $bundle::class;
  476. $bundlesMetadata[$name] = [
  477. 'path' => $bundle->getPath(),
  478. 'namespace' => $bundle->getNamespace(),
  479. ];
  480. }
  481. return [
  482. 'kernel.project_dir' => realpath($this->getProjectDir()) ?: $this->getProjectDir(),
  483. 'kernel.environment' => $this->environment,
  484. 'kernel.runtime_environment' => '%env(default:kernel.environment:APP_RUNTIME_ENV)%',
  485. 'kernel.runtime_mode' => '%env(query_string:default:container.runtime_mode:APP_RUNTIME_MODE)%',
  486. 'kernel.runtime_mode.web' => '%env(bool:default::key:web:default:kernel.runtime_mode:)%',
  487. 'kernel.runtime_mode.cli' => '%env(not:default:kernel.runtime_mode.web:)%',
  488. 'kernel.runtime_mode.worker' => '%env(bool:default::key:worker:default:kernel.runtime_mode:)%',
  489. 'kernel.debug' => $this->debug,
  490. 'kernel.build_dir' => realpath($buildDir = $this->warmupDir ?: $this->getBuildDir()) ?: $buildDir,
  491. 'kernel.cache_dir' => realpath($cacheDir = ($this->getCacheDir() === $this->getBuildDir() ? ($this->warmupDir ?: $this->getCacheDir()) : $this->getCacheDir())) ?: $cacheDir,
  492. 'kernel.logs_dir' => realpath($this->getLogDir()) ?: $this->getLogDir(),
  493. 'kernel.bundles' => $bundles,
  494. 'kernel.bundles_metadata' => $bundlesMetadata,
  495. 'kernel.charset' => $this->getCharset(),
  496. 'kernel.container_class' => $this->getContainerClass(),
  497. ];
  498. }
  499. /**
  500. * Builds the service container.
  501. *
  502. * @throws \RuntimeException
  503. */
  504. protected function buildContainer(): ContainerBuilder
  505. {
  506. foreach (['cache' => $this->getCacheDir(), 'build' => $this->warmupDir ?: $this->getBuildDir(), 'logs' => $this->getLogDir()] as $name => $dir) {
  507. if (!is_dir($dir)) {
  508. if (false === @mkdir($dir, 0777, true) && !is_dir($dir)) {
  509. throw new \RuntimeException(\sprintf('Unable to create the "%s" directory (%s).', $name, $dir));
  510. }
  511. } elseif (!is_writable($dir)) {
  512. throw new \RuntimeException(\sprintf('Unable to write in the "%s" directory (%s).', $name, $dir));
  513. }
  514. }
  515. $container = $this->getContainerBuilder();
  516. $container->addObjectResource($this);
  517. $this->prepareContainer($container);
  518. $this->registerContainerConfiguration($this->getContainerLoader($container));
  519. return $container;
  520. }
  521. /**
  522. * Prepares the ContainerBuilder before it is compiled.
  523. */
  524. protected function prepareContainer(ContainerBuilder $container): void
  525. {
  526. $extensions = [];
  527. foreach ($this->bundles as $bundle) {
  528. if ($extension = $bundle->getContainerExtension()) {
  529. $container->registerExtension($extension);
  530. }
  531. if ($this->debug) {
  532. $container->addObjectResource($bundle);
  533. }
  534. }
  535. foreach ($this->bundles as $bundle) {
  536. $bundle->build($container);
  537. }
  538. $this->build($container);
  539. foreach ($container->getExtensions() as $extension) {
  540. $extensions[] = $extension->getAlias();
  541. }
  542. // ensure these extensions are implicitly loaded
  543. $container->getCompilerPassConfig()->setMergePass(new MergeExtensionConfigurationPass($extensions));
  544. }
  545. /**
  546. * Gets a new ContainerBuilder instance used to build the service container.
  547. */
  548. protected function getContainerBuilder(): ContainerBuilder
  549. {
  550. $container = new ContainerBuilder();
  551. $container->getParameterBag()->add($this->getKernelParameters());
  552. if ($this instanceof ExtensionInterface) {
  553. $container->registerExtension($this);
  554. }
  555. if ($this instanceof CompilerPassInterface) {
  556. $container->addCompilerPass($this, PassConfig::TYPE_BEFORE_OPTIMIZATION, -10000);
  557. }
  558. return $container;
  559. }
  560. /**
  561. * Dumps the service container to PHP code in the cache.
  562. *
  563. * @param string $class The name of the class to generate
  564. * @param string $baseClass The name of the container's base class
  565. */
  566. protected function dumpContainer(ConfigCache $cache, ContainerBuilder $container, string $class, string $baseClass): void
  567. {
  568. // cache the container
  569. $dumper = new PhpDumper($container);
  570. $buildParameters = [];
  571. foreach ($container->getCompilerPassConfig()->getPasses() as $pass) {
  572. if ($pass instanceof RemoveBuildParametersPass) {
  573. $buildParameters = array_merge($buildParameters, $pass->getRemovedParameters());
  574. }
  575. }
  576. $content = $dumper->dump([
  577. 'class' => $class,
  578. 'base_class' => $baseClass,
  579. 'file' => $cache->getPath(),
  580. 'as_files' => true,
  581. 'debug' => $this->debug,
  582. 'inline_factories' => $buildParameters['.container.dumper.inline_factories'] ?? false,
  583. 'inline_class_loader' => $buildParameters['.container.dumper.inline_class_loader'] ?? $this->debug,
  584. 'build_time' => $container->hasParameter('kernel.container_build_time') ? $container->getParameter('kernel.container_build_time') : time(),
  585. 'preload_classes' => array_map('get_class', $this->bundles),
  586. ]);
  587. $rootCode = array_pop($content);
  588. $dir = \dirname($cache->getPath()).'/';
  589. $fs = new Filesystem();
  590. foreach ($content as $file => $code) {
  591. $fs->dumpFile($dir.$file, $code);
  592. @chmod($dir.$file, 0666 & ~umask());
  593. }
  594. $legacyFile = \dirname($dir.key($content)).'.legacy';
  595. if (is_file($legacyFile)) {
  596. @unlink($legacyFile);
  597. }
  598. $cache->write($rootCode, $container->getResources());
  599. }
  600. /**
  601. * Returns a loader for the container.
  602. */
  603. protected function getContainerLoader(ContainerInterface $container): DelegatingLoader
  604. {
  605. $env = $this->getEnvironment();
  606. $locator = new FileLocator($this);
  607. $resolver = new LoaderResolver([
  608. new XmlFileLoader($container, $locator, $env),
  609. new YamlFileLoader($container, $locator, $env),
  610. new IniFileLoader($container, $locator, $env),
  611. new PhpFileLoader($container, $locator, $env, class_exists(ConfigBuilderGenerator::class) ? new ConfigBuilderGenerator($this->getBuildDir()) : null),
  612. new GlobFileLoader($container, $locator, $env),
  613. new DirectoryLoader($container, $locator, $env),
  614. new ClosureLoader($container, $env),
  615. ]);
  616. return new DelegatingLoader($resolver);
  617. }
  618. private function preBoot(): ContainerInterface
  619. {
  620. if ($this->debug) {
  621. $this->startTime = microtime(true);
  622. }
  623. if ($this->debug && !isset($_ENV['SHELL_VERBOSITY']) && !isset($_SERVER['SHELL_VERBOSITY'])) {
  624. if (\function_exists('putenv')) {
  625. putenv('SHELL_VERBOSITY=3');
  626. }
  627. $_ENV['SHELL_VERBOSITY'] = 3;
  628. $_SERVER['SHELL_VERBOSITY'] = 3;
  629. }
  630. $this->initializeBundles();
  631. $this->initializeContainer();
  632. $container = $this->container;
  633. if ($container->hasParameter('kernel.trusted_hosts') && $trustedHosts = $container->getParameter('kernel.trusted_hosts')) {
  634. Request::setTrustedHosts(\is_array($trustedHosts) ? $trustedHosts : preg_split('/\s*+,\s*+(?![^{]*})/', $trustedHosts));
  635. }
  636. if ($container->hasParameter('kernel.trusted_proxies') && $container->hasParameter('kernel.trusted_headers') && $trustedProxies = $container->getParameter('kernel.trusted_proxies')) {
  637. $trustedHeaders = $container->getParameter('kernel.trusted_headers');
  638. if (\is_string($trustedHeaders)) {
  639. $trustedHeaders = array_map('trim', explode(',', $trustedHeaders));
  640. }
  641. if (\is_array($trustedHeaders)) {
  642. $trustedHeaderSet = 0;
  643. foreach ($trustedHeaders as $header) {
  644. if (!\defined($const = Request::class.'::HEADER_'.strtr(strtoupper($header), '-', '_'))) {
  645. throw new \InvalidArgumentException(\sprintf('The trusted header "%s" is not supported.', $header));
  646. }
  647. $trustedHeaderSet |= \constant($const);
  648. }
  649. } else {
  650. $trustedHeaderSet = $trustedHeaders ?? (Request::HEADER_X_FORWARDED_FOR | Request::HEADER_X_FORWARDED_PORT | Request::HEADER_X_FORWARDED_PROTO);
  651. }
  652. Request::setTrustedProxies(\is_array($trustedProxies) ? $trustedProxies : array_map('trim', explode(',', $trustedProxies)), $trustedHeaderSet);
  653. }
  654. return $container;
  655. }
  656. public function __sleep(): array
  657. {
  658. return ['environment', 'debug'];
  659. }
  660. public function __wakeup(): void
  661. {
  662. if (\is_object($this->environment) || \is_object($this->debug)) {
  663. throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
  664. }
  665. $this->__construct($this->environment, $this->debug);
  666. }
  667. }