FrameworkExtension.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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\Bundle\FrameworkBundle\DependencyInjection;
  11. use Symfony\Component\DependencyInjection\ContainerBuilder;
  12. use Symfony\Component\DependencyInjection\Definition;
  13. use Symfony\Component\DependencyInjection\Parameter;
  14. use Symfony\Component\DependencyInjection\Reference;
  15. use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
  16. use Symfony\Component\Config\Resource\FileResource;
  17. use Symfony\Component\Finder\Finder;
  18. use Symfony\Component\HttpKernel\DependencyInjection\Extension;
  19. use Symfony\Component\Config\FileLocator;
  20. use Symfony\Component\Config\Definition\Processor;
  21. /**
  22. * FrameworkExtension.
  23. *
  24. * @author Fabien Potencier <fabien@symfony.com>
  25. * @author Jeremy Mikola <jmikola@gmail.com>
  26. */
  27. class FrameworkExtension extends Extension
  28. {
  29. /**
  30. * Responds to the app.config configuration parameter.
  31. *
  32. * @param array $configs
  33. * @param ContainerBuilder $container
  34. */
  35. public function load(array $configs, ContainerBuilder $container)
  36. {
  37. $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
  38. $loader->load('web.xml');
  39. $loader->load('form.xml');
  40. $loader->load('services.xml');
  41. // A translator must always be registered (as support is included by
  42. // default in the Form component). If disabled, an identity translator
  43. // will be used and everything will still work as expected.
  44. $loader->load('translation.xml');
  45. if ($container->getParameter('kernel.debug')) {
  46. $loader->load('debug.xml');
  47. $container->setDefinition('event_dispatcher', $container->findDefinition('debug.event_dispatcher'));
  48. $container->setAlias('debug.event_dispatcher', 'event_dispatcher');
  49. }
  50. $processor = new Processor();
  51. $configuration = new Configuration($container->getParameter('kernel.debug'));
  52. $config = $processor->processConfiguration($configuration, $configs);
  53. $container->setParameter('kernel.cache_warmup', $config['cache_warmer']);
  54. if (isset($config['charset'])) {
  55. $container->setParameter('kernel.charset', $config['charset']);
  56. }
  57. if (isset($config['document_root'])) {
  58. $container->setParameter('document_root', $config['document_root']);
  59. }
  60. if (isset($config['error_handler'])) {
  61. if (false === $config['error_handler']) {
  62. $container->getDefinition('error_handler')->setMethodCalls(array());
  63. } else {
  64. $container
  65. ->getDefinition('error_handler')->addMethodCall('register', array())
  66. ->setArgument(0, $config['error_handler'])
  67. ;
  68. }
  69. }
  70. $container->getDefinition('exception_listener')->setArgument(0, $config['exception_controller']);
  71. if (!empty($config['test'])) {
  72. $loader->load('test.xml');
  73. if (isset($config['session'])) {
  74. $config['session']['storage_id'] = 'array';
  75. }
  76. }
  77. if (isset($config['csrf_protection'])) {
  78. $this->registerCsrfProtectionConfiguration($config['csrf_protection'], $container);
  79. }
  80. if (isset($config['esi'])) {
  81. $this->registerEsiConfiguration($config['esi'], $loader);
  82. }
  83. if (isset($config['profiler'])) {
  84. $this->registerProfilerConfiguration($config['profiler'], $container, $loader);
  85. }
  86. if (isset($config['router'])) {
  87. $this->registerRouterConfiguration($config['router'], $container, $loader);
  88. }
  89. if (isset($config['session'])) {
  90. $this->registerSessionConfiguration($config['session'], $container, $loader);
  91. }
  92. if (isset($config['templating'])) {
  93. $this->registerTemplatingConfiguration($config['templating'], $config['ide'], $container, $loader);
  94. }
  95. if (isset($config['translator'])) {
  96. $this->registerTranslatorConfiguration($config['translator'], $container);
  97. }
  98. if (isset($config['validation'])) {
  99. $this->registerValidationConfiguration($config['validation'], $container, $loader);
  100. }
  101. $this->addClassesToCompile(array(
  102. 'Symfony\\Component\\HttpFoundation\\ParameterBag',
  103. 'Symfony\\Component\\HttpFoundation\\HeaderBag',
  104. 'Symfony\\Component\\HttpFoundation\\Request',
  105. 'Symfony\\Component\\HttpFoundation\\Response',
  106. 'Symfony\\Component\\HttpFoundation\\ResponseHeaderBag',
  107. 'Symfony\\Component\\EventDispatcher\\EventDispatcherInterface',
  108. 'Symfony\\Component\\EventDispatcher\\EventDispatcher',
  109. 'Symfony\\Component\\EventDispatcher\\Event',
  110. 'Symfony\\Component\\EventDispatcher\\EventSubscriberInterface',
  111. 'Symfony\\Component\\HttpKernel\\HttpKernel',
  112. 'Symfony\\Component\\HttpKernel\\ResponseListener',
  113. 'Symfony\\Component\\HttpKernel\\Controller\\ControllerResolver',
  114. 'Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface',
  115. 'Symfony\\Component\\HttpKernel\\Event\\KernelEvent',
  116. 'Symfony\\Component\\HttpKernel\\Event\\FilterControllerEvent',
  117. 'Symfony\\Component\\HttpKernel\\Event\\FilterResponseEvent',
  118. 'Symfony\\Component\\HttpKernel\\Event\\GetResponseEvent',
  119. 'Symfony\\Component\\HttpKernel\\Event\\GetResponseForControllerResultEvent',
  120. 'Symfony\\Component\\HttpKernel\\Event\\GetResponseForExceptionEvent',
  121. 'Symfony\\Component\\HttpKernel\\Events',
  122. 'Symfony\\Bundle\\FrameworkBundle\\RequestListener',
  123. 'Symfony\\Bundle\\FrameworkBundle\\Controller\\ControllerNameParser',
  124. 'Symfony\\Bundle\\FrameworkBundle\\Controller\\ControllerResolver',
  125. 'Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller',
  126. 'Symfony\\Bundle\\FrameworkBundle\\ContainerAwareEventDispatcher',
  127. ));
  128. }
  129. /**
  130. * Loads the CSRF protection configuration.
  131. *
  132. * @param array $config A CSRF protection configuration array
  133. * @param ContainerBuilder $container A ContainerBuilder instance
  134. */
  135. private function registerCsrfProtectionConfiguration(array $config, ContainerBuilder $container)
  136. {
  137. foreach (array('enabled', 'field_name', 'secret') as $key) {
  138. if (isset($config[$key])) {
  139. $container->setParameter('form.csrf_protection.'.$key, $config[$key]);
  140. }
  141. }
  142. }
  143. /**
  144. * Loads the ESI configuration.
  145. *
  146. * @param array $config An ESI configuration array
  147. * @param XmlFileLoader $loader An XmlFileLoader instance
  148. */
  149. private function registerEsiConfiguration(array $config, XmlFileLoader $loader)
  150. {
  151. if (!empty($config['enabled'])) {
  152. $loader->load('esi.xml');
  153. }
  154. }
  155. /**
  156. * Loads the profiler configuration.
  157. *
  158. * @param array $config A profiler configuration array
  159. * @param ContainerBuilder $container A ContainerBuilder instance
  160. * @param XmlFileLoader $loader An XmlFileLoader instance
  161. */
  162. private function registerProfilerConfiguration(array $config, ContainerBuilder $container, XmlFileLoader $loader)
  163. {
  164. $loader->load('profiling.xml');
  165. $loader->load('collectors.xml');
  166. $container->getDefinition('profiler_listener')
  167. ->setArgument(2, $config['only_exceptions'])
  168. ->setArgument(3, $config['only_master_requests'])
  169. ;
  170. // Choose storage class based on the DSN
  171. $supported = array(
  172. 'sqlite' => 'Symfony\Component\HttpKernel\Profiler\SqliteProfilerStorage',
  173. 'mysql' => 'Symfony\Component\HttpKernel\Profiler\MysqlProfilerStorage',
  174. );
  175. list($class, ) = explode(':', $config['dsn']);
  176. if (!isset($supported[$class])) {
  177. throw new \LogicException(sprintf('Driver "%s" is not supported for the profiler.', $class));
  178. }
  179. $container->getDefinition('profiler.storage')
  180. ->setArgument(0, $config['dsn'])
  181. ->setArgument(1, $config['username'])
  182. ->setArgument(2, $config['password'])
  183. ->setArgument(3, $config['lifetime'])
  184. ->setClass($supported[$class])
  185. ;
  186. if (isset($config['matcher'])) {
  187. if (isset($config['matcher']['service'])) {
  188. $container->setAlias('profiler.request_matcher', $config['matcher']['service']);
  189. } elseif (isset($config['matcher']['ip']) || isset($config['matcher']['path'])) {
  190. $definition = $container->register('profiler.request_matcher', 'Symfony\\Component\\HttpFoundation\\RequestMatcher');
  191. $definition->setPublic(false);
  192. if (isset($config['matcher']['ip'])) {
  193. $definition->addMethodCall('matchIp', array($config['matcher']['ip']));
  194. }
  195. if (isset($config['matcher']['path'])) {
  196. $definition->addMethodCall('matchPath', array($config['matcher']['path']));
  197. }
  198. }
  199. }
  200. }
  201. /**
  202. * Loads the router configuration.
  203. *
  204. * @param array $config A router configuration array
  205. * @param ContainerBuilder $container A ContainerBuilder instance
  206. * @param XmlFileLoader $loader An XmlFileLoader instance
  207. */
  208. private function registerRouterConfiguration(array $config, ContainerBuilder $container, XmlFileLoader $loader)
  209. {
  210. $loader->load('routing.xml');
  211. $container->setParameter('routing.resource', $config['resource']);
  212. if (isset($config['type'])) {
  213. $container->setParameter('router.options.resource_type', $config['type']);
  214. }
  215. if ($config['cache_warmer']) {
  216. $container->getDefinition('router.cache_warmer')->addTag('kernel.cache_warmer');
  217. $container->setAlias('router', 'router.cached');
  218. }
  219. $this->addClassesToCompile(array(
  220. 'Symfony\\Component\\Routing\\RouterInterface',
  221. 'Symfony\\Component\\Routing\\Matcher\\UrlMatcherInterface',
  222. 'Symfony\\Component\\Routing\\Matcher\\UrlMatcher',
  223. 'Symfony\\Component\\Routing\\Generator\\UrlGeneratorInterface',
  224. 'Symfony\\Component\\Routing\\Generator\\UrlGenerator',
  225. $container->findDefinition('router')->getClass(),
  226. ));
  227. }
  228. /**
  229. * Loads the session configuration.
  230. *
  231. * @param array $config A session configuration array
  232. * @param ContainerBuilder $container A ContainerBuilder instance
  233. * @param XmlFileLoader $loader An XmlFileLoader instance
  234. */
  235. private function registerSessionConfiguration(array $config, ContainerBuilder $container, XmlFileLoader $loader)
  236. {
  237. $loader->load('session.xml');
  238. if (!empty($config['auto_start'])) {
  239. $container->getDefinition('session')->addMethodCall('start');
  240. }
  241. if (isset($config['class'])) {
  242. $container->setParameter('session.class', $config['class']);
  243. }
  244. $container->getDefinition('session')->setArgument(1, $config['default_locale']);
  245. $container->setAlias('session.storage', 'session.storage.'.$config['storage_id']);
  246. $options = $container->getParameter('session.storage.'.$config['storage_id'].'.options');
  247. foreach (array('name', 'lifetime', 'path', 'domain', 'secure', 'httponly', 'db_table', 'db_id_col', 'db_data_col', 'db_time_col') as $key) {
  248. if (isset($config[$key])) {
  249. $options[$key] = $config[$key];
  250. }
  251. }
  252. $container->setParameter('session.storage.'.$config['storage_id'].'.options', $options);
  253. $this->addClassesToCompile(array(
  254. 'Symfony\\Component\\HttpFoundation\\Session',
  255. 'Symfony\\Component\\HttpFoundation\\SessionStorage\\SessionStorageInterface',
  256. $container->getParameter('session.class'),
  257. ));
  258. }
  259. /**
  260. * Loads the templating configuration.
  261. *
  262. * @param array $config A templating configuration array
  263. * @param ContainerBuilder $container A ContainerBuilder instance
  264. * @param XmlFileLoader $loader An XmlFileLoader instance
  265. */
  266. private function registerTemplatingConfiguration(array $config, $ide, ContainerBuilder $container, XmlFileLoader $loader)
  267. {
  268. $loader->load('templating.xml');
  269. $loader->load('templating_php.xml');
  270. $links = array(
  271. 'textmate' => 'txmt://open?url=file://%f&line=%l',
  272. 'macvim' => 'mvim://open?url=file://%f&line=%l',
  273. );
  274. $container
  275. ->getDefinition('templating.helper.code')
  276. ->setArgument(0, str_replace('%', '%%', isset($links[$ide]) ? $links[$ide] : $ide))
  277. ;
  278. if ($container->getParameter('kernel.debug')) {
  279. $loader->load('templating_debug.xml');
  280. }
  281. $packages = array();
  282. foreach ($config['packages'] as $name => $package) {
  283. $packages[$name] = new Definition('%templating.asset_package.class%', array(
  284. $package['base_urls'],
  285. $package['version'],
  286. ));
  287. }
  288. $container
  289. ->getDefinition('templating.helper.assets')
  290. ->setArgument(1, isset($config['assets_base_urls']) ? $config['assets_base_urls'] : array())
  291. ->setArgument(2, $config['assets_version'])
  292. ->setArgument(3, $packages)
  293. ;
  294. if (!empty($config['loaders'])) {
  295. $loaders = array_map(function($loader) { return new Reference($loader); }, $config['loaders']);
  296. // Use a delegation unless only a single loader was registered
  297. if (1 === count($loaders)) {
  298. $container->setAlias('templating.loader', (string) reset($loaders));
  299. } else {
  300. $container->getDefinition('templating.loader.chain')->addArgument($loaders);
  301. $container->setAlias('templating.loader', 'templating.loader.chain');
  302. }
  303. }
  304. if (isset($config['cache'])) {
  305. // Wrap the existing loader with cache (must happen after loaders are registered)
  306. $container->setDefinition('templating.loader.wrapped', $container->findDefinition('templating.loader'));
  307. $loaderCache = $container->getDefinition('templating.loader.cache');
  308. $loaderCache->setArgument(1, $config['cache']);
  309. $container->setDefinition('templating.loader', $loaderCache);
  310. }
  311. if ($config['cache_warmer']) {
  312. $container->getDefinition('templating.cache_warmer.template_paths')->addTag('kernel.cache_warmer');
  313. $container->setAlias('templating.locator', 'templating.locator.cached');
  314. }
  315. $this->addClassesToCompile(array(
  316. 'Symfony\\Bundle\\FrameworkBundle\\Templating\\EngineInterface',
  317. 'Symfony\\Component\\Templating\\TemplateNameParserInterface',
  318. 'Symfony\\Component\\Templating\\TemplateNameParser',
  319. 'Symfony\\Component\\Templating\\EngineInterface',
  320. 'Symfony\\Component\\Config\\FileLocatorInterface',
  321. 'Symfony\\Component\\Templating\\TemplateReferenceInterface',
  322. 'Symfony\\Component\\Templating\\TemplateReference',
  323. 'Symfony\\Bundle\\FrameworkBundle\\Templating\\TemplateReference',
  324. 'Symfony\\Bundle\\FrameworkBundle\\Templating\\TemplateNameParser',
  325. $container->findDefinition('templating.locator')->getClass(),
  326. ));
  327. if (in_array('php', $config['engines'], true)) {
  328. $this->addClassesToCompile(array(
  329. 'Symfony\\Component\\Templating\\PhpEngine',
  330. 'Symfony\\Component\\Templating\\Loader\\LoaderInterface',
  331. 'Symfony\\Component\\Templating\\Storage\\Storage',
  332. 'Symfony\\Component\\Templating\\Storage\\FileStorage',
  333. 'Symfony\\Bundle\\FrameworkBundle\\Templating\\PhpEngine',
  334. 'Symfony\\Bundle\\FrameworkBundle\\Templating\\Loader\\FilesystemLoader',
  335. ));
  336. }
  337. $container->setParameter('templating.engines', $config['engines']);
  338. $engines = array_map(function($engine) { return new Reference('templating.engine.'.$engine); }, $config['engines']);
  339. // Use a delegation unless only a single engine was registered
  340. if (1 === count($engines)) {
  341. $container->setAlias('templating', (string) reset($engines));
  342. } else {
  343. $container->getDefinition('templating.engine.delegating')->setArgument(1, $engines);
  344. $container->setAlias('templating', 'templating.engine.delegating');
  345. }
  346. }
  347. /**
  348. * Loads the translator configuration.
  349. *
  350. * @param array $config A translator configuration array
  351. * @param ContainerBuilder $container A ContainerBuilder instance
  352. */
  353. private function registerTranslatorConfiguration(array $config, ContainerBuilder $container)
  354. {
  355. if (!empty($config['enabled'])) {
  356. // Use the "real" translator instead of the identity default
  357. $container->setDefinition('translator', $translator = $container->findDefinition('translator.real'));
  358. $translator->addMethodCall('setFallbackLocale', array($config['fallback']));
  359. // Discover translation directories
  360. $dirs = array();
  361. foreach ($container->getParameter('kernel.bundles') as $bundle) {
  362. $reflection = new \ReflectionClass($bundle);
  363. if (is_dir($dir = dirname($reflection->getFilename()).'/Resources/translations')) {
  364. $dirs[] = $dir;
  365. }
  366. }
  367. if (is_dir($dir = $container->getParameter('kernel.root_dir').'/translations')) {
  368. $dirs[] = $dir;
  369. }
  370. // Register translation resources
  371. $resources = array();
  372. if ($dirs) {
  373. $finder = new Finder();
  374. $finder->files()->filter(function (\SplFileInfo $file) { return 2 === substr_count($file->getBasename(), '.'); })->in($dirs);
  375. foreach ($finder as $file) {
  376. // filename is domain.locale.format
  377. list($domain, $locale, $format) = explode('.', $file->getBasename());
  378. $resources[] = array($format, (string) $file, $locale, $domain);
  379. }
  380. }
  381. $container->setParameter('translation.resources', $resources);
  382. }
  383. }
  384. /**
  385. * Loads the validator configuration.
  386. *
  387. * @param array $config A validation configuration array
  388. * @param ContainerBuilder $container A ContainerBuilder instance
  389. * @param XmlFileLoader $loader An XmlFileLoader instance
  390. */
  391. private function registerValidationConfiguration(array $config, ContainerBuilder $container, XmlFileLoader $loader)
  392. {
  393. if (empty($config['enabled'])) {
  394. return;
  395. }
  396. $loader->load('validator.xml');
  397. $container
  398. ->getDefinition('validator.mapping.loader.xml_files_loader')
  399. ->setArgument(0, $this->getValidatorXmlMappingFiles($container))
  400. ;
  401. $container
  402. ->getDefinition('validator.mapping.loader.yaml_files_loader')
  403. ->setArgument(0, $this->getValidatorYamlMappingFiles($container))
  404. ;
  405. if (isset($config['annotations'])) {
  406. $namespaces = array('assert' => 'Symfony\\Component\\Validator\\Constraints\\');
  407. // Register prefixes for constraint namespaces
  408. if (!empty($config['annotations']['namespaces'])) {
  409. $namespaces = array_merge($namespaces, $config['annotations']['namespaces']);
  410. }
  411. // Register annotation loader
  412. $container
  413. ->getDefinition('validator.mapping.loader.annotation_loader')
  414. ->setArgument(0, $namespaces)
  415. ;
  416. $loaderChain = $container->getDefinition('validator.mapping.loader.loader_chain');
  417. $arguments = $loaderChain->getArguments();
  418. array_unshift($arguments[0], new Reference('validator.mapping.loader.annotation_loader'));
  419. $loaderChain->setArguments($arguments);
  420. }
  421. }
  422. private function getValidatorXmlMappingFiles(ContainerBuilder $container)
  423. {
  424. $files = array(__DIR__.'/../../../Component/Form/Resources/config/validation.xml');
  425. $container->addResource(new FileResource($files[0]));
  426. foreach ($container->getParameter('kernel.bundles') as $bundle) {
  427. $reflection = new \ReflectionClass($bundle);
  428. if (file_exists($file = dirname($reflection->getFilename()).'/Resources/config/validation.xml')) {
  429. $files[] = realpath($file);
  430. $container->addResource(new FileResource($file));
  431. }
  432. }
  433. return $files;
  434. }
  435. private function getValidatorYamlMappingFiles(ContainerBuilder $container)
  436. {
  437. $files = array();
  438. foreach ($container->getParameter('kernel.bundles') as $bundle) {
  439. $reflection = new \ReflectionClass($bundle);
  440. if (file_exists($file = dirname($reflection->getFilename()).'/Resources/config/validation.yml')) {
  441. $yamlMappingFiles[] = realpath($file);
  442. $container->addResource(new FileResource($file));
  443. }
  444. }
  445. return $files;
  446. }
  447. /**
  448. * Returns the base path for the XSD files.
  449. *
  450. * @return string The XSD base path
  451. */
  452. public function getXsdValidationBasePath()
  453. {
  454. return __DIR__.'/../Resources/config/schema';
  455. }
  456. public function getNamespace()
  457. {
  458. return 'http://symfony.com/schema/dic/symfony';
  459. }
  460. }