XmlFileLoaderTest.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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\DependencyInjection\Tests\Loader;
  11. use PHPUnit\Framework\TestCase;
  12. use Symfony\Component\Config\FileLocator;
  13. use Symfony\Component\Config\Loader\LoaderResolver;
  14. use Symfony\Component\DependencyInjection\ContainerBuilder;
  15. use Symfony\Component\DependencyInjection\ContainerInterface;
  16. use Symfony\Component\DependencyInjection\Loader\IniFileLoader;
  17. use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
  18. use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
  19. use Symfony\Component\DependencyInjection\Reference;
  20. use Symfony\Component\ExpressionLanguage\Expression;
  21. class XmlFileLoaderTest extends TestCase
  22. {
  23. protected static $fixturesPath;
  24. public static function setUpBeforeClass()
  25. {
  26. self::$fixturesPath = realpath(__DIR__.'/../Fixtures/');
  27. require_once self::$fixturesPath.'/includes/foo.php';
  28. require_once self::$fixturesPath.'/includes/ProjectExtension.php';
  29. require_once self::$fixturesPath.'/includes/ProjectWithXsdExtension.php';
  30. }
  31. public function testLoad()
  32. {
  33. $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/ini'));
  34. try {
  35. $loader->load('foo.xml');
  36. $this->fail('->load() throws an InvalidArgumentException if the loaded file does not exist');
  37. } catch (\Exception $e) {
  38. $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the loaded file does not exist');
  39. $this->assertStringStartsWith('The file "foo.xml" does not exist (in:', $e->getMessage(), '->load() throws an InvalidArgumentException if the loaded file does not exist');
  40. }
  41. }
  42. public function testParseFile()
  43. {
  44. $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/ini'));
  45. $r = new \ReflectionObject($loader);
  46. $m = $r->getMethod('parseFileToDOM');
  47. $m->setAccessible(true);
  48. try {
  49. $m->invoke($loader, self::$fixturesPath.'/ini/parameters.ini');
  50. $this->fail('->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file');
  51. } catch (\Exception $e) {
  52. $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file');
  53. $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'parameters.ini'), $e->getMessage(), '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file');
  54. $e = $e->getPrevious();
  55. $this->assertInstanceOf('InvalidArgumentException', $e, '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file');
  56. $this->assertStringStartsWith('[ERROR 4] Start tag expected, \'<\' not found (in', $e->getMessage(), '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file');
  57. }
  58. $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/xml'));
  59. try {
  60. $m->invoke($loader, self::$fixturesPath.'/xml/nonvalid.xml');
  61. $this->fail('->parseFileToDOM() throws an InvalidArgumentException if the loaded file does not validate the XSD');
  62. } catch (\Exception $e) {
  63. $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->parseFileToDOM() throws an InvalidArgumentException if the loaded file does not validate the XSD');
  64. $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'nonvalid.xml'), $e->getMessage(), '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file');
  65. $e = $e->getPrevious();
  66. $this->assertInstanceOf('InvalidArgumentException', $e, '->parseFileToDOM() throws an InvalidArgumentException if the loaded file does not validate the XSD');
  67. $this->assertStringStartsWith('[ERROR 1845] Element \'nonvalid\': No matching global declaration available for the validation root. (in', $e->getMessage(), '->parseFileToDOM() throws an InvalidArgumentException if the loaded file does not validate the XSD');
  68. }
  69. $xml = $m->invoke($loader, self::$fixturesPath.'/xml/services1.xml');
  70. $this->assertInstanceOf('DOMDocument', $xml, '->parseFileToDOM() returns an SimpleXMLElement object');
  71. }
  72. public function testLoadWithExternalEntitiesDisabled()
  73. {
  74. $disableEntities = libxml_disable_entity_loader(true);
  75. $containerBuilder = new ContainerBuilder();
  76. $loader = new XmlFileLoader($containerBuilder, new FileLocator(self::$fixturesPath.'/xml'));
  77. $loader->load('services2.xml');
  78. libxml_disable_entity_loader($disableEntities);
  79. $this->assertGreaterThan(0, $containerBuilder->getParameterBag()->all(), 'Parameters can be read from the config file.');
  80. }
  81. public function testLoadParameters()
  82. {
  83. $container = new ContainerBuilder();
  84. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  85. $loader->load('services2.xml');
  86. $actual = $container->getParameterBag()->all();
  87. $expected = array(
  88. 'a string',
  89. 'foo' => 'bar',
  90. 'values' => array(
  91. 0,
  92. 'integer' => 4,
  93. 100 => null,
  94. 'true',
  95. true,
  96. false,
  97. 'on',
  98. 'off',
  99. 'float' => 1.3,
  100. 1000.3,
  101. 'a string',
  102. array('foo', 'bar'),
  103. ),
  104. 'mixedcase' => array('MixedCaseKey' => 'value'),
  105. 'constant' => PHP_EOL,
  106. );
  107. $this->assertEquals($expected, $actual, '->load() converts XML values to PHP ones');
  108. }
  109. public function testLoadImports()
  110. {
  111. $container = new ContainerBuilder();
  112. $resolver = new LoaderResolver(array(
  113. new IniFileLoader($container, new FileLocator(self::$fixturesPath.'/ini')),
  114. new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yml')),
  115. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')),
  116. ));
  117. $loader->setResolver($resolver);
  118. $loader->load('services4.xml');
  119. $actual = $container->getParameterBag()->all();
  120. $expected = array(
  121. 'a string',
  122. 'foo' => 'bar',
  123. 'values' => array(
  124. 0,
  125. 'integer' => 4,
  126. 100 => null,
  127. 'true',
  128. true,
  129. false,
  130. 'on',
  131. 'off',
  132. 'float' => 1.3,
  133. 1000.3,
  134. 'a string',
  135. array('foo', 'bar'),
  136. ),
  137. 'mixedcase' => array('MixedCaseKey' => 'value'),
  138. 'constant' => PHP_EOL,
  139. 'bar' => '%foo%',
  140. 'imported_from_ini' => true,
  141. 'imported_from_yaml' => true,
  142. );
  143. $this->assertEquals(array_keys($expected), array_keys($actual), '->load() imports and merges imported files');
  144. // Bad import throws no exception due to ignore_errors value.
  145. $loader->load('services4_bad_import.xml');
  146. }
  147. public function testLoadAnonymousServices()
  148. {
  149. $container = new ContainerBuilder();
  150. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  151. $loader->load('services5.xml');
  152. $services = $container->getDefinitions();
  153. $this->assertCount(6, $services, '->load() attributes unique ids to anonymous services');
  154. // anonymous service as an argument
  155. $args = $services['foo']->getArguments();
  156. $this->assertCount(1, $args, '->load() references anonymous services as "normal" ones');
  157. $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Reference', $args[0], '->load() converts anonymous services to references to "normal" services');
  158. $this->assertArrayHasKey((string) $args[0], $services, '->load() makes a reference to the created ones');
  159. $inner = $services[(string) $args[0]];
  160. $this->assertEquals('BarClass', $inner->getClass(), '->load() uses the same configuration as for the anonymous ones');
  161. $this->assertFalse($inner->isPublic());
  162. // inner anonymous services
  163. $args = $inner->getArguments();
  164. $this->assertCount(1, $args, '->load() references anonymous services as "normal" ones');
  165. $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Reference', $args[0], '->load() converts anonymous services to references to "normal" services');
  166. $this->assertArrayHasKey((string) $args[0], $services, '->load() makes a reference to the created ones');
  167. $inner = $services[(string) $args[0]];
  168. $this->assertEquals('BazClass', $inner->getClass(), '->load() uses the same configuration as for the anonymous ones');
  169. $this->assertFalse($inner->isPublic());
  170. // anonymous service as a property
  171. $properties = $services['foo']->getProperties();
  172. $property = $properties['p'];
  173. $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Reference', $property, '->load() converts anonymous services to references to "normal" services');
  174. $this->assertArrayHasKey((string) $property, $services, '->load() makes a reference to the created ones');
  175. $inner = $services[(string) $property];
  176. $this->assertEquals('BuzClass', $inner->getClass(), '->load() uses the same configuration as for the anonymous ones');
  177. $this->assertFalse($inner->isPublic());
  178. // "wild" service
  179. $service = $container->findTaggedServiceIds('biz_tag');
  180. $this->assertCount(1, $service);
  181. foreach ($service as $id => $tag) {
  182. $service = $container->getDefinition($id);
  183. }
  184. $this->assertEquals('BizClass', $service->getClass(), '->load() uses the same configuration as for the anonymous ones');
  185. $this->assertTrue($service->isPublic());
  186. // anonymous services are shared when using decoration definitions
  187. $container->compile();
  188. $services = $container->getDefinitions();
  189. $fooArgs = $services['foo']->getArguments();
  190. $barArgs = $services['bar']->getArguments();
  191. $this->assertSame($fooArgs[0], $barArgs[0]);
  192. }
  193. /**
  194. * @group legacy
  195. */
  196. public function testLegacyLoadServices()
  197. {
  198. $container = new ContainerBuilder();
  199. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  200. $loader->load('legacy-services6.xml');
  201. $services = $container->getDefinitions();
  202. $this->assertEquals('FooClass', $services['constructor']->getClass());
  203. $this->assertEquals('getInstance', $services['constructor']->getFactoryMethod());
  204. $this->assertNull($services['factory_service']->getClass());
  205. $this->assertEquals('baz_factory', $services['factory_service']->getFactoryService());
  206. $this->assertEquals('getInstance', $services['factory_service']->getFactoryMethod());
  207. $this->assertEquals('container', $services['scope.container']->getScope());
  208. $this->assertEquals('custom', $services['scope.custom']->getScope());
  209. $this->assertEquals('prototype', $services['scope.prototype']->getScope());
  210. $this->assertTrue($services['request']->isSynthetic(), '->load() parses the synthetic flag');
  211. $this->assertTrue($services['request']->isSynchronized(), '->load() parses the synchronized flag');
  212. $this->assertTrue($services['request']->isLazy(), '->load() parses the lazy flag');
  213. $this->assertNull($services['request']->getDecoratedService());
  214. }
  215. public function testLoadServices()
  216. {
  217. $container = new ContainerBuilder();
  218. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  219. $loader->load('services6.xml');
  220. $services = $container->getDefinitions();
  221. $this->assertArrayHasKey('foo', $services, '->load() parses <service> elements');
  222. $this->assertFalse($services['not_shared']->isShared(), '->load() parses shared flag');
  223. $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Definition', $services['foo'], '->load() converts <service> element to Definition instances');
  224. $this->assertEquals('FooClass', $services['foo']->getClass(), '->load() parses the class attribute');
  225. $this->assertEquals('%path%/foo.php', $services['file']->getFile(), '->load() parses the file tag');
  226. $this->assertEquals(array('foo', new Reference('foo'), array(true, false)), $services['arguments']->getArguments(), '->load() parses the argument tags');
  227. $this->assertEquals('sc_configure', $services['configurator1']->getConfigurator(), '->load() parses the configurator tag');
  228. $this->assertEquals(array(new Reference('baz', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, false), 'configure'), $services['configurator2']->getConfigurator(), '->load() parses the configurator tag');
  229. $this->assertEquals(array('BazClass', 'configureStatic'), $services['configurator3']->getConfigurator(), '->load() parses the configurator tag');
  230. $this->assertEquals(array(array('setBar', array()), array('setBar', array(new Expression('service("foo").foo() ~ (container.hasParameter("foo") ? parameter("foo") : "default")')))), $services['method_call1']->getMethodCalls(), '->load() parses the method_call tag');
  231. $this->assertEquals(array(array('setBar', array('foo', new Reference('foo'), array(true, false)))), $services['method_call2']->getMethodCalls(), '->load() parses the method_call tag');
  232. $this->assertEquals('factory', $services['new_factory1']->getFactory(), '->load() parses the factory tag');
  233. $this->assertEquals(array(new Reference('baz', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, false), 'getClass'), $services['new_factory2']->getFactory(), '->load() parses the factory tag');
  234. $this->assertEquals(array('BazClass', 'getInstance'), $services['new_factory3']->getFactory(), '->load() parses the factory tag');
  235. $aliases = $container->getAliases();
  236. $this->assertArrayHasKey('alias_for_foo', $aliases, '->load() parses <service> elements');
  237. $this->assertEquals('foo', (string) $aliases['alias_for_foo'], '->load() parses aliases');
  238. $this->assertTrue($aliases['alias_for_foo']->isPublic());
  239. $this->assertArrayHasKey('another_alias_for_foo', $aliases);
  240. $this->assertEquals('foo', (string) $aliases['another_alias_for_foo']);
  241. $this->assertFalse($aliases['another_alias_for_foo']->isPublic());
  242. $this->assertEquals(array('decorated', null, 0), $services['decorator_service']->getDecoratedService());
  243. $this->assertEquals(array('decorated', 'decorated.pif-pouf', 0), $services['decorator_service_with_name']->getDecoratedService());
  244. $this->assertEquals(array('decorated', 'decorated.pif-pouf', 5), $services['decorator_service_with_name_and_priority']->getDecoratedService());
  245. }
  246. public function testParsesTags()
  247. {
  248. $container = new ContainerBuilder();
  249. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  250. $loader->load('services10.xml');
  251. $services = $container->findTaggedServiceIds('foo_tag');
  252. $this->assertCount(1, $services);
  253. foreach ($services as $id => $tagAttributes) {
  254. foreach ($tagAttributes as $attributes) {
  255. $this->assertArrayHasKey('other_option', $attributes);
  256. $this->assertEquals('lorem', $attributes['other_option']);
  257. $this->assertArrayHasKey('other-option', $attributes, 'unnormalized tag attributes should not be removed');
  258. $this->assertEquals('ciz', $attributes['some_option'], 'no overriding should be done when normalizing');
  259. $this->assertEquals('cat', $attributes['some-option']);
  260. $this->assertArrayNotHasKey('an_other_option', $attributes, 'normalization should not be done when an underscore is already found');
  261. }
  262. }
  263. }
  264. /**
  265. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  266. */
  267. public function testParseTagsWithoutNameThrowsException()
  268. {
  269. $container = new ContainerBuilder();
  270. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  271. $loader->load('tag_without_name.xml');
  272. }
  273. /**
  274. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  275. * @expectedExceptionMessageRegExp /The tag name for service ".+" in .* must be a non-empty string/
  276. */
  277. public function testParseTagWithEmptyNameThrowsException()
  278. {
  279. $container = new ContainerBuilder();
  280. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  281. $loader->load('tag_with_empty_name.xml');
  282. }
  283. public function testDeprecated()
  284. {
  285. $container = new ContainerBuilder();
  286. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  287. $loader->load('services_deprecated.xml');
  288. $this->assertTrue($container->getDefinition('foo')->isDeprecated());
  289. $message = 'The "foo" service is deprecated. You should stop using it, as it will soon be removed.';
  290. $this->assertSame($message, $container->getDefinition('foo')->getDeprecationMessage('foo'));
  291. $this->assertTrue($container->getDefinition('bar')->isDeprecated());
  292. $message = 'The "bar" service is deprecated.';
  293. $this->assertSame($message, $container->getDefinition('bar')->getDeprecationMessage('bar'));
  294. }
  295. public function testConvertDomElementToArray()
  296. {
  297. $doc = new \DOMDocument('1.0');
  298. $doc->loadXML('<foo>bar</foo>');
  299. $this->assertEquals('bar', XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
  300. $doc = new \DOMDocument('1.0');
  301. $doc->loadXML('<foo foo="bar" />');
  302. $this->assertEquals(array('foo' => 'bar'), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
  303. $doc = new \DOMDocument('1.0');
  304. $doc->loadXML('<foo><foo>bar</foo></foo>');
  305. $this->assertEquals(array('foo' => 'bar'), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
  306. $doc = new \DOMDocument('1.0');
  307. $doc->loadXML('<foo><foo>bar<foo>bar</foo></foo></foo>');
  308. $this->assertEquals(array('foo' => array('value' => 'bar', 'foo' => 'bar')), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
  309. $doc = new \DOMDocument('1.0');
  310. $doc->loadXML('<foo><foo></foo></foo>');
  311. $this->assertEquals(array('foo' => null), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
  312. $doc = new \DOMDocument('1.0');
  313. $doc->loadXML('<foo><foo><!-- foo --></foo></foo>');
  314. $this->assertEquals(array('foo' => null), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
  315. $doc = new \DOMDocument('1.0');
  316. $doc->loadXML('<foo><foo foo="bar"/><foo foo="bar"/></foo>');
  317. $this->assertEquals(array('foo' => array(array('foo' => 'bar'), array('foo' => 'bar'))), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
  318. }
  319. public function testExtensions()
  320. {
  321. $container = new ContainerBuilder();
  322. $container->registerExtension(new \ProjectExtension());
  323. $container->registerExtension(new \ProjectWithXsdExtension());
  324. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  325. // extension without an XSD
  326. $loader->load('extensions/services1.xml');
  327. $container->compile();
  328. $services = $container->getDefinitions();
  329. $parameters = $container->getParameterBag()->all();
  330. $this->assertArrayHasKey('project.service.bar', $services, '->load() parses extension elements');
  331. $this->assertArrayHasKey('project.parameter.bar', $parameters, '->load() parses extension elements');
  332. $this->assertEquals('BAR', $services['project.service.foo']->getClass(), '->load() parses extension elements');
  333. $this->assertEquals('BAR', $parameters['project.parameter.foo'], '->load() parses extension elements');
  334. // extension with an XSD
  335. $container = new ContainerBuilder();
  336. $container->registerExtension(new \ProjectExtension());
  337. $container->registerExtension(new \ProjectWithXsdExtension());
  338. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  339. $loader->load('extensions/services2.xml');
  340. $container->compile();
  341. $services = $container->getDefinitions();
  342. $parameters = $container->getParameterBag()->all();
  343. $this->assertArrayHasKey('project.service.bar', $services, '->load() parses extension elements');
  344. $this->assertArrayHasKey('project.parameter.bar', $parameters, '->load() parses extension elements');
  345. $this->assertEquals('BAR', $services['project.service.foo']->getClass(), '->load() parses extension elements');
  346. $this->assertEquals('BAR', $parameters['project.parameter.foo'], '->load() parses extension elements');
  347. $container = new ContainerBuilder();
  348. $container->registerExtension(new \ProjectExtension());
  349. $container->registerExtension(new \ProjectWithXsdExtension());
  350. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  351. // extension with an XSD (does not validate)
  352. try {
  353. $loader->load('extensions/services3.xml');
  354. $this->fail('->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
  355. } catch (\Exception $e) {
  356. $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
  357. $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'services3.xml'), $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
  358. $e = $e->getPrevious();
  359. $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
  360. $this->assertContains('The attribute \'bar\' is not allowed', $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
  361. }
  362. // non-registered extension
  363. try {
  364. $loader->load('extensions/services4.xml');
  365. $this->fail('->load() throws an InvalidArgumentException if the tag is not valid');
  366. } catch (\Exception $e) {
  367. $this->assertInstanceOf('\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the tag is not valid');
  368. $this->assertStringStartsWith('There is no extension able to load the configuration for "project:bar" (in', $e->getMessage(), '->load() throws an InvalidArgumentException if the tag is not valid');
  369. }
  370. }
  371. public function testExtensionInPhar()
  372. {
  373. if (\extension_loaded('suhosin') && false === strpos(ini_get('suhosin.executor.include.whitelist'), 'phar')) {
  374. $this->markTestSkipped('To run this test, add "phar" to the "suhosin.executor.include.whitelist" settings in your php.ini file.');
  375. }
  376. if (\defined('HHVM_VERSION')) {
  377. $this->markTestSkipped('HHVM makes this test conflict with those run in separate processes.');
  378. }
  379. require_once self::$fixturesPath.'/includes/ProjectWithXsdExtensionInPhar.phar';
  380. // extension with an XSD in PHAR archive
  381. $container = new ContainerBuilder();
  382. $container->registerExtension(new \ProjectWithXsdExtensionInPhar());
  383. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  384. $loader->load('extensions/services6.xml');
  385. // extension with an XSD in PHAR archive (does not validate)
  386. try {
  387. $loader->load('extensions/services7.xml');
  388. $this->fail('->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
  389. } catch (\Exception $e) {
  390. $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
  391. $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'services7.xml'), $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
  392. $e = $e->getPrevious();
  393. $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
  394. $this->assertContains('The attribute \'bar\' is not allowed', $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
  395. }
  396. }
  397. public function testSupports()
  398. {
  399. $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator());
  400. $this->assertTrue($loader->supports('foo.xml'), '->supports() returns true if the resource is loadable');
  401. $this->assertFalse($loader->supports('foo.foo'), '->supports() returns true if the resource is loadable');
  402. }
  403. public function testNoNamingConflictsForAnonymousServices()
  404. {
  405. $container = new ContainerBuilder();
  406. $loader1 = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml/extension1'));
  407. $loader1->load('services.xml');
  408. $services = $container->getDefinitions();
  409. $this->assertCount(2, $services, '->load() attributes unique ids to anonymous services');
  410. $loader2 = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml/extension2'));
  411. $loader2->load('services.xml');
  412. $services = $container->getDefinitions();
  413. $this->assertCount(4, $services, '->load() attributes unique ids to anonymous services');
  414. $services = $container->getDefinitions();
  415. $args1 = $services['extension1.foo']->getArguments();
  416. $inner1 = $services[(string) $args1[0]];
  417. $this->assertEquals('BarClass1', $inner1->getClass(), '->load() uses the same configuration as for the anonymous ones');
  418. $args2 = $services['extension2.foo']->getArguments();
  419. $inner2 = $services[(string) $args2[0]];
  420. $this->assertEquals('BarClass2', $inner2->getClass(), '->load() uses the same configuration as for the anonymous ones');
  421. }
  422. public function testDocTypeIsNotAllowed()
  423. {
  424. $container = new ContainerBuilder();
  425. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  426. // document types are not allowed.
  427. try {
  428. $loader->load('withdoctype.xml');
  429. $this->fail('->load() throws an InvalidArgumentException if the configuration contains a document type');
  430. } catch (\Exception $e) {
  431. $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration contains a document type');
  432. $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'withdoctype.xml'), $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration contains a document type');
  433. $e = $e->getPrevious();
  434. $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration contains a document type');
  435. $this->assertSame('Document types are not allowed.', $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration contains a document type');
  436. }
  437. }
  438. public function testXmlNamespaces()
  439. {
  440. $container = new ContainerBuilder();
  441. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  442. $loader->load('namespaces.xml');
  443. $services = $container->getDefinitions();
  444. $this->assertArrayHasKey('foo', $services, '->load() parses <srv:service> elements');
  445. $this->assertCount(1, $services['foo']->getTag('foo.tag'), '->load parses <srv:tag> elements');
  446. $this->assertEquals(array(array('setBar', array('foo'))), $services['foo']->getMethodCalls(), '->load() parses the <srv:call> tag');
  447. }
  448. public function testLoadIndexedArguments()
  449. {
  450. $container = new ContainerBuilder();
  451. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  452. $loader->load('services14.xml');
  453. $this->assertEquals(array('index_0' => 'app'), $container->findDefinition('logger')->getArguments());
  454. }
  455. public function testLoadInlinedServices()
  456. {
  457. $container = new ContainerBuilder();
  458. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  459. $loader->load('services21.xml');
  460. $foo = $container->getDefinition('foo');
  461. $fooFactory = $foo->getFactory();
  462. $this->assertInstanceOf('Symfony\Component\DependencyInjection\Definition', $fooFactory[0]);
  463. $this->assertSame('FooFactory', $fooFactory[0]->getClass());
  464. $this->assertSame('createFoo', $fooFactory[1]);
  465. $fooFactoryFactory = $fooFactory[0]->getFactory();
  466. $this->assertInstanceOf('Symfony\Component\DependencyInjection\Definition', $fooFactoryFactory[0]);
  467. $this->assertSame('Foobar', $fooFactoryFactory[0]->getClass());
  468. $this->assertSame('createFooFactory', $fooFactoryFactory[1]);
  469. $fooConfigurator = $foo->getConfigurator();
  470. $this->assertInstanceOf('Symfony\Component\DependencyInjection\Definition', $fooConfigurator[0]);
  471. $this->assertSame('Bar', $fooConfigurator[0]->getClass());
  472. $this->assertSame('configureFoo', $fooConfigurator[1]);
  473. $barConfigurator = $fooConfigurator[0]->getConfigurator();
  474. $this->assertInstanceOf('Symfony\Component\DependencyInjection\Definition', $barConfigurator[0]);
  475. $this->assertSame('Baz', $barConfigurator[0]->getClass());
  476. $this->assertSame('configureBar', $barConfigurator[1]);
  477. }
  478. public function testType()
  479. {
  480. $container = new ContainerBuilder();
  481. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  482. $loader->load('services22.xml');
  483. $this->assertEquals(array('Bar', 'Baz'), $container->getDefinition('foo')->getAutowiringTypes());
  484. }
  485. public function testAutowire()
  486. {
  487. $container = new ContainerBuilder();
  488. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  489. $loader->load('services23.xml');
  490. $this->assertTrue($container->getDefinition('bar')->isAutowired());
  491. }
  492. public function testArgumentWithKeyOutsideCollection()
  493. {
  494. $container = new ContainerBuilder();
  495. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  496. $loader->load('with_key_outside_collection.xml');
  497. $this->assertSame(array('type' => 'foo', 'bar'), $container->getDefinition('foo')->getArguments());
  498. }
  499. }