PageRenderTime 29ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Symfony/Component/HttpKernel/Kernel.php

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