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

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