FrameworkExtension.php 22 KB

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