Kernel.php 27 KB

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