Kernel.php 21 KB

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