Kernel.php 21 KB

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