Kernel.php 22KB

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