Kernel.php 30 KB

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