Kernel.php 32 KB

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