Kernel.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  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.6';
  58. const VERSION_ID = 30306;
  59. const MAJOR_VERSION = 3;
  60. const MINOR_VERSION = 3;
  61. const RELEASE_VERSION = 6;
  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. if (isset($collectedLogs[$message])) {
  476. ++$collectedLogs[$message]['count'];
  477. return;
  478. }
  479. $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
  480. // Clean the trace by removing first frames added by the error handler itself.
  481. for ($i = 0; isset($backtrace[$i]); ++$i) {
  482. if (isset($backtrace[$i]['file'], $backtrace[$i]['line']) && $backtrace[$i]['line'] === $line && $backtrace[$i]['file'] === $file) {
  483. $backtrace = array_slice($backtrace, 1 + $i);
  484. break;
  485. }
  486. }
  487. $collectedLogs[$message] = array(
  488. 'type' => $type,
  489. 'message' => $message,
  490. 'file' => $file,
  491. 'line' => $line,
  492. 'trace' => $backtrace,
  493. 'count' => 1,
  494. );
  495. });
  496. }
  497. try {
  498. $container = null;
  499. $container = $this->buildContainer();
  500. $container->compile();
  501. } finally {
  502. if ($this->debug) {
  503. restore_error_handler();
  504. file_put_contents($this->getCacheDir().'/'.$class.'Deprecations.log', serialize(array_values($collectedLogs)));
  505. file_put_contents($this->getCacheDir().'/'.$class.'Compiler.log', null !== $container ? implode("\n", $container->getCompiler()->getLog()) : '');
  506. }
  507. }
  508. $this->dumpContainer($cache, $container, $class, $this->getContainerBaseClass());
  509. $fresh = false;
  510. }
  511. require_once $cache->getPath();
  512. $this->container = new $class();
  513. $this->container->set('kernel', $this);
  514. if (!$fresh && $this->container->has('cache_warmer')) {
  515. $this->container->get('cache_warmer')->warmUp($this->container->getParameter('kernel.cache_dir'));
  516. }
  517. }
  518. /**
  519. * Returns the kernel parameters.
  520. *
  521. * @return array An array of kernel parameters
  522. */
  523. protected function getKernelParameters()
  524. {
  525. $bundles = array();
  526. $bundlesMetadata = array();
  527. foreach ($this->bundles as $name => $bundle) {
  528. $bundles[$name] = get_class($bundle);
  529. $bundlesMetadata[$name] = array(
  530. 'parent' => $bundle->getParent(),
  531. 'path' => $bundle->getPath(),
  532. 'namespace' => $bundle->getNamespace(),
  533. );
  534. }
  535. return array_merge(
  536. array(
  537. 'kernel.root_dir' => realpath($this->rootDir) ?: $this->rootDir,
  538. 'kernel.project_dir' => realpath($this->getProjectDir()) ?: $this->getProjectDir(),
  539. 'kernel.environment' => $this->environment,
  540. 'kernel.debug' => $this->debug,
  541. 'kernel.name' => $this->name,
  542. 'kernel.cache_dir' => realpath($this->getCacheDir()) ?: $this->getCacheDir(),
  543. 'kernel.logs_dir' => realpath($this->getLogDir()) ?: $this->getLogDir(),
  544. 'kernel.bundles' => $bundles,
  545. 'kernel.bundles_metadata' => $bundlesMetadata,
  546. 'kernel.charset' => $this->getCharset(),
  547. 'kernel.container_class' => $this->getContainerClass(),
  548. ),
  549. $this->getEnvParameters(false)
  550. );
  551. }
  552. /**
  553. * Gets the environment parameters.
  554. *
  555. * Only the parameters starting with "SYMFONY__" are considered.
  556. *
  557. * @return array An array of parameters
  558. *
  559. * @deprecated since version 3.3, to be removed in 4.0
  560. */
  561. protected function getEnvParameters()
  562. {
  563. if (0 === func_num_args() || func_get_arg(0)) {
  564. @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);
  565. }
  566. $parameters = array();
  567. foreach ($_SERVER as $key => $value) {
  568. if (0 === strpos($key, 'SYMFONY__')) {
  569. @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);
  570. $parameters[strtolower(str_replace('__', '.', substr($key, 9)))] = $value;
  571. }
  572. }
  573. return $parameters;
  574. }
  575. /**
  576. * Builds the service container.
  577. *
  578. * @return ContainerBuilder The compiled service container
  579. *
  580. * @throws \RuntimeException
  581. */
  582. protected function buildContainer()
  583. {
  584. foreach (array('cache' => $this->getCacheDir(), 'logs' => $this->getLogDir()) as $name => $dir) {
  585. if (!is_dir($dir)) {
  586. if (false === @mkdir($dir, 0777, true) && !is_dir($dir)) {
  587. throw new \RuntimeException(sprintf("Unable to create the %s directory (%s)\n", $name, $dir));
  588. }
  589. } elseif (!is_writable($dir)) {
  590. throw new \RuntimeException(sprintf("Unable to write in the %s directory (%s)\n", $name, $dir));
  591. }
  592. }
  593. $container = $this->getContainerBuilder();
  594. $container->addObjectResource($this);
  595. $this->prepareContainer($container);
  596. if (null !== $cont = $this->registerContainerConfiguration($this->getContainerLoader($container))) {
  597. $container->merge($cont);
  598. }
  599. $container->addCompilerPass(new AddAnnotatedClassesToCachePass($this));
  600. $container->addResource(new EnvParametersResource('SYMFONY__'));
  601. return $container;
  602. }
  603. /**
  604. * Prepares the ContainerBuilder before it is compiled.
  605. *
  606. * @param ContainerBuilder $container A ContainerBuilder instance
  607. */
  608. protected function prepareContainer(ContainerBuilder $container)
  609. {
  610. $extensions = array();
  611. foreach ($this->bundles as $bundle) {
  612. if ($extension = $bundle->getContainerExtension()) {
  613. $container->registerExtension($extension);
  614. $extensions[] = $extension->getAlias();
  615. }
  616. if ($this->debug) {
  617. $container->addObjectResource($bundle);
  618. }
  619. }
  620. foreach ($this->bundles as $bundle) {
  621. $bundle->build($container);
  622. }
  623. $this->build($container);
  624. // ensure these extensions are implicitly loaded
  625. $container->getCompilerPassConfig()->setMergePass(new MergeExtensionConfigurationPass($extensions));
  626. }
  627. /**
  628. * Gets a new ContainerBuilder instance used to build the service container.
  629. *
  630. * @return ContainerBuilder
  631. */
  632. protected function getContainerBuilder()
  633. {
  634. $container = new ContainerBuilder();
  635. $container->getParameterBag()->add($this->getKernelParameters());
  636. if (class_exists('ProxyManager\Configuration') && class_exists('Symfony\Bridge\ProxyManager\LazyProxy\Instantiator\RuntimeInstantiator')) {
  637. $container->setProxyInstantiator(new RuntimeInstantiator());
  638. }
  639. return $container;
  640. }
  641. /**
  642. * Dumps the service container to PHP code in the cache.
  643. *
  644. * @param ConfigCache $cache The config cache
  645. * @param ContainerBuilder $container The service container
  646. * @param string $class The name of the class to generate
  647. * @param string $baseClass The name of the container's base class
  648. */
  649. protected function dumpContainer(ConfigCache $cache, ContainerBuilder $container, $class, $baseClass)
  650. {
  651. // cache the container
  652. $dumper = new PhpDumper($container);
  653. if (class_exists('ProxyManager\Configuration') && class_exists('Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper\ProxyDumper')) {
  654. $dumper->setProxyDumper(new ProxyDumper(md5($cache->getPath())));
  655. }
  656. $content = $dumper->dump(array('class' => $class, 'base_class' => $baseClass, 'file' => $cache->getPath(), 'debug' => $this->debug));
  657. $cache->write($content, $container->getResources());
  658. }
  659. /**
  660. * Returns a loader for the container.
  661. *
  662. * @param ContainerInterface $container The service container
  663. *
  664. * @return DelegatingLoader The loader
  665. */
  666. protected function getContainerLoader(ContainerInterface $container)
  667. {
  668. $locator = new FileLocator($this);
  669. $resolver = new LoaderResolver(array(
  670. new XmlFileLoader($container, $locator),
  671. new YamlFileLoader($container, $locator),
  672. new IniFileLoader($container, $locator),
  673. new PhpFileLoader($container, $locator),
  674. new GlobFileLoader($locator),
  675. new DirectoryLoader($container, $locator),
  676. new ClosureLoader($container),
  677. ));
  678. return new DelegatingLoader($resolver);
  679. }
  680. /**
  681. * Removes comments from a PHP source string.
  682. *
  683. * We don't use the PHP php_strip_whitespace() function
  684. * as we want the content to be readable and well-formatted.
  685. *
  686. * @param string $source A PHP string
  687. *
  688. * @return string The PHP string with the comments removed
  689. */
  690. public static function stripComments($source)
  691. {
  692. if (!function_exists('token_get_all')) {
  693. return $source;
  694. }
  695. $rawChunk = '';
  696. $output = '';
  697. $tokens = token_get_all($source);
  698. $ignoreSpace = false;
  699. for ($i = 0; isset($tokens[$i]); ++$i) {
  700. $token = $tokens[$i];
  701. if (!isset($token[1]) || 'b"' === $token) {
  702. $rawChunk .= $token;
  703. } elseif (T_START_HEREDOC === $token[0]) {
  704. $output .= $rawChunk.$token[1];
  705. do {
  706. $token = $tokens[++$i];
  707. $output .= isset($token[1]) && 'b"' !== $token ? $token[1] : $token;
  708. } while ($token[0] !== T_END_HEREDOC);
  709. $rawChunk = '';
  710. } elseif (T_WHITESPACE === $token[0]) {
  711. if ($ignoreSpace) {
  712. $ignoreSpace = false;
  713. continue;
  714. }
  715. // replace multiple new lines with a single newline
  716. $rawChunk .= preg_replace(array('/\n{2,}/S'), "\n", $token[1]);
  717. } elseif (in_array($token[0], array(T_COMMENT, T_DOC_COMMENT))) {
  718. $ignoreSpace = true;
  719. } else {
  720. $rawChunk .= $token[1];
  721. // The PHP-open tag already has a new-line
  722. if (T_OPEN_TAG === $token[0]) {
  723. $ignoreSpace = true;
  724. }
  725. }
  726. }
  727. $output .= $rawChunk;
  728. if (\PHP_VERSION_ID >= 70000) {
  729. // PHP 7 memory manager will not release after token_get_all(), see https://bugs.php.net/70098
  730. unset($tokens, $rawChunk);
  731. gc_mem_caches();
  732. }
  733. return $output;
  734. }
  735. public function serialize()
  736. {
  737. return serialize(array($this->environment, $this->debug));
  738. }
  739. public function unserialize($data)
  740. {
  741. if (\PHP_VERSION_ID >= 70000) {
  742. list($environment, $debug) = unserialize($data, array('allowed_classes' => false));
  743. } else {
  744. list($environment, $debug) = unserialize($data);
  745. }
  746. $this->__construct($environment, $debug);
  747. }
  748. }