PageRenderTime 26ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

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

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