Kernel.php 22 KB

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