Sen descrición

Kernel.php 30KB

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