XmlFileLoaderTest.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  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\DependencyInjection\Argument\IteratorArgument;
  13. use Symfony\Component\DependencyInjection\ContainerBuilder;
  14. use Symfony\Component\DependencyInjection\Reference;
  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\Config\Loader\LoaderResolver;
  19. use Symfony\Component\Config\FileLocator;
  20. use Symfony\Component\Config\Resource\FileResource;
  21. use Symfony\Component\Config\Resource\GlobResource;
  22. use Symfony\Component\DependencyInjection\Tests\Fixtures\CaseSensitiveClass;
  23. use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype;
  24. use Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy;
  25. use Symfony\Component\ExpressionLanguage\Expression;
  26. class XmlFileLoaderTest extends TestCase
  27. {
  28. protected static $fixturesPath;
  29. public static function setUpBeforeClass()
  30. {
  31. self::$fixturesPath = realpath(__DIR__.'/../Fixtures/');
  32. require_once self::$fixturesPath.'/includes/foo.php';
  33. require_once self::$fixturesPath.'/includes/ProjectExtension.php';
  34. require_once self::$fixturesPath.'/includes/ProjectWithXsdExtension.php';
  35. }
  36. public function testLoad()
  37. {
  38. $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/ini'));
  39. try {
  40. $loader->load('foo.xml');
  41. $this->fail('->load() throws an InvalidArgumentException if the loaded file does not exist');
  42. } catch (\Exception $e) {
  43. $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the loaded file does not exist');
  44. $this->assertStringStartsWith('The file "foo.xml" does not exist (in:', $e->getMessage(), '->load() throws an InvalidArgumentException if the loaded file does not exist');
  45. }
  46. }
  47. public function testParseFile()
  48. {
  49. $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/ini'));
  50. $r = new \ReflectionObject($loader);
  51. $m = $r->getMethod('parseFileToDOM');
  52. $m->setAccessible(true);
  53. try {
  54. $m->invoke($loader, self::$fixturesPath.'/ini/parameters.ini');
  55. $this->fail('->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file');
  56. } catch (\Exception $e) {
  57. $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file');
  58. $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');
  59. $e = $e->getPrevious();
  60. $this->assertInstanceOf('InvalidArgumentException', $e, '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file');
  61. $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');
  62. }
  63. $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/xml'));
  64. try {
  65. $m->invoke($loader, self::$fixturesPath.'/xml/nonvalid.xml');
  66. $this->fail('->parseFileToDOM() throws an InvalidArgumentException if the loaded file does not validate the XSD');
  67. } catch (\Exception $e) {
  68. $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->parseFileToDOM() throws an InvalidArgumentException if the loaded file does not validate the XSD');
  69. $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');
  70. $e = $e->getPrevious();
  71. $this->assertInstanceOf('InvalidArgumentException', $e, '->parseFileToDOM() throws an InvalidArgumentException if the loaded file does not validate the XSD');
  72. $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');
  73. }
  74. $xml = $m->invoke($loader, self::$fixturesPath.'/xml/services1.xml');
  75. $this->assertInstanceOf('DOMDocument', $xml, '->parseFileToDOM() returns an SimpleXMLElement object');
  76. }
  77. public function testLoadWithExternalEntitiesDisabled()
  78. {
  79. $disableEntities = libxml_disable_entity_loader(true);
  80. $containerBuilder = new ContainerBuilder();
  81. $loader = new XmlFileLoader($containerBuilder, new FileLocator(self::$fixturesPath.'/xml'));
  82. $loader->load('services2.xml');
  83. libxml_disable_entity_loader($disableEntities);
  84. $this->assertGreaterThan(0, $containerBuilder->getParameterBag()->all(), 'Parameters can be read from the config file.');
  85. }
  86. public function testLoadParameters()
  87. {
  88. $container = new ContainerBuilder();
  89. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  90. $loader->load('services2.xml');
  91. $actual = $container->getParameterBag()->all();
  92. $expected = array(
  93. 'a string',
  94. 'foo' => 'bar',
  95. 'values' => array(
  96. 0,
  97. 'integer' => 4,
  98. 100 => null,
  99. 'true',
  100. true,
  101. false,
  102. 'on',
  103. 'off',
  104. 'float' => 1.3,
  105. 1000.3,
  106. 'a string',
  107. array('foo', 'bar'),
  108. ),
  109. 'mixedcase' => array('MixedCaseKey' => 'value'),
  110. 'constant' => PHP_EOL,
  111. );
  112. $this->assertEquals($expected, $actual, '->load() converts XML values to PHP ones');
  113. }
  114. public function testLoadImports()
  115. {
  116. $container = new ContainerBuilder();
  117. $resolver = new LoaderResolver(array(
  118. new IniFileLoader($container, new FileLocator(self::$fixturesPath.'/ini')),
  119. new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yml')),
  120. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')),
  121. ));
  122. $loader->setResolver($resolver);
  123. $loader->load('services4.xml');
  124. $actual = $container->getParameterBag()->all();
  125. $expected = array(
  126. 'a string',
  127. 'foo' => 'bar',
  128. 'values' => array(
  129. 0,
  130. 'integer' => 4,
  131. 100 => null,
  132. 'true',
  133. true,
  134. false,
  135. 'on',
  136. 'off',
  137. 'float' => 1.3,
  138. 1000.3,
  139. 'a string',
  140. array('foo', 'bar'),
  141. ),
  142. 'mixedcase' => array('MixedCaseKey' => 'value'),
  143. 'constant' => PHP_EOL,
  144. 'bar' => '%foo%',
  145. 'imported_from_ini' => true,
  146. 'imported_from_yaml' => true,
  147. 'with_wrong_ext' => 'from yaml',
  148. );
  149. $this->assertEquals(array_keys($expected), array_keys($actual), '->load() imports and merges imported files');
  150. $this->assertTrue($actual['imported_from_ini']);
  151. // Bad import throws no exception due to ignore_errors value.
  152. $loader->load('services4_bad_import.xml');
  153. }
  154. public function testLoadAnonymousServices()
  155. {
  156. $container = new ContainerBuilder();
  157. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  158. $loader->load('services5.xml');
  159. $services = $container->getDefinitions();
  160. $this->assertCount(7, $services, '->load() attributes unique ids to anonymous services');
  161. // anonymous service as an argument
  162. $args = $services['foo']->getArguments();
  163. $this->assertCount(1, $args, '->load() references anonymous services as "normal" ones');
  164. $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Reference', $args[0], '->load() converts anonymous services to references to "normal" services');
  165. $this->assertArrayHasKey((string) $args[0], $services, '->load() makes a reference to the created ones');
  166. $inner = $services[(string) $args[0]];
  167. $this->assertEquals('BarClass', $inner->getClass(), '->load() uses the same configuration as for the anonymous ones');
  168. $this->assertFalse($inner->isPublic());
  169. // inner anonymous services
  170. $args = $inner->getArguments();
  171. $this->assertCount(1, $args, '->load() references anonymous services as "normal" ones');
  172. $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Reference', $args[0], '->load() converts anonymous services to references to "normal" services');
  173. $this->assertArrayHasKey((string) $args[0], $services, '->load() makes a reference to the created ones');
  174. $inner = $services[(string) $args[0]];
  175. $this->assertEquals('BazClass', $inner->getClass(), '->load() uses the same configuration as for the anonymous ones');
  176. $this->assertFalse($inner->isPublic());
  177. // anonymous service as a property
  178. $properties = $services['foo']->getProperties();
  179. $property = $properties['p'];
  180. $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Reference', $property, '->load() converts anonymous services to references to "normal" services');
  181. $this->assertArrayHasKey((string) $property, $services, '->load() makes a reference to the created ones');
  182. $inner = $services[(string) $property];
  183. $this->assertEquals('BuzClass', $inner->getClass(), '->load() uses the same configuration as for the anonymous ones');
  184. $this->assertFalse($inner->isPublic());
  185. // "wild" service
  186. $service = $container->findTaggedServiceIds('biz_tag');
  187. $this->assertCount(1, $service);
  188. foreach ($service as $id => $tag) {
  189. $service = $container->getDefinition($id);
  190. }
  191. $this->assertEquals('BizClass', $service->getClass(), '->load() uses the same configuration as for the anonymous ones');
  192. $this->assertTrue($service->isPublic());
  193. // anonymous services are shared when using decoration definitions
  194. $container->compile();
  195. $services = $container->getDefinitions();
  196. $fooArgs = $services['foo']->getArguments();
  197. $barArgs = $services['bar']->getArguments();
  198. $this->assertSame($fooArgs[0], $barArgs[0]);
  199. }
  200. public function testLoadServices()
  201. {
  202. $container = new ContainerBuilder();
  203. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  204. $loader->load('services6.xml');
  205. $services = $container->getDefinitions();
  206. $this->assertArrayHasKey('foo', $services, '->load() parses <service> elements');
  207. $this->assertFalse($services['not_shared']->isShared(), '->load() parses shared flag');
  208. $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Definition', $services['foo'], '->load() converts <service> element to Definition instances');
  209. $this->assertEquals('FooClass', $services['foo']->getClass(), '->load() parses the class attribute');
  210. $this->assertEquals('%path%/foo.php', $services['file']->getFile(), '->load() parses the file tag');
  211. $this->assertEquals(array('foo', new Reference('foo'), array(true, false)), $services['arguments']->getArguments(), '->load() parses the argument tags');
  212. $this->assertEquals('sc_configure', $services['configurator1']->getConfigurator(), '->load() parses the configurator tag');
  213. $this->assertEquals(array(new Reference('baz'), 'configure'), $services['configurator2']->getConfigurator(), '->load() parses the configurator tag');
  214. $this->assertEquals(array('BazClass', 'configureStatic'), $services['configurator3']->getConfigurator(), '->load() parses the configurator tag');
  215. $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');
  216. $this->assertEquals(array(array('setBar', array('foo', new Reference('foo'), array(true, false)))), $services['method_call2']->getMethodCalls(), '->load() parses the method_call tag');
  217. $this->assertEquals('factory', $services['new_factory1']->getFactory(), '->load() parses the factory tag');
  218. $this->assertEquals(array(new Reference('baz'), 'getClass'), $services['new_factory2']->getFactory(), '->load() parses the factory tag');
  219. $this->assertEquals(array('BazClass', 'getInstance'), $services['new_factory3']->getFactory(), '->load() parses the factory tag');
  220. $this->assertSame(array(null, 'getInstance'), $services['new_factory4']->getFactory(), '->load() accepts factory tag without class');
  221. $aliases = $container->getAliases();
  222. $this->assertArrayHasKey('alias_for_foo', $aliases, '->load() parses <service> elements');
  223. $this->assertEquals('foo', (string) $aliases['alias_for_foo'], '->load() parses aliases');
  224. $this->assertTrue($aliases['alias_for_foo']->isPublic());
  225. $this->assertArrayHasKey('another_alias_for_foo', $aliases);
  226. $this->assertEquals('foo', (string) $aliases['another_alias_for_foo']);
  227. $this->assertFalse($aliases['another_alias_for_foo']->isPublic());
  228. $this->assertEquals(array('decorated', null, 0), $services['decorator_service']->getDecoratedService());
  229. $this->assertEquals(array('decorated', 'decorated.pif-pouf', 0), $services['decorator_service_with_name']->getDecoratedService());
  230. $this->assertEquals(array('decorated', 'decorated.pif-pouf', 5), $services['decorator_service_with_name_and_priority']->getDecoratedService());
  231. }
  232. public function testParsesIteratorArgument()
  233. {
  234. $container = new ContainerBuilder();
  235. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  236. $loader->load('services9.xml');
  237. $lazyDefinition = $container->getDefinition('lazy_context');
  238. $this->assertEquals(array(new IteratorArgument(array('k1' => new Reference('foo.baz'), 'k2' => new Reference('service_container'))), new IteratorArgument(array())), $lazyDefinition->getArguments(), '->load() parses lazy arguments');
  239. }
  240. public function testParsesTags()
  241. {
  242. $container = new ContainerBuilder();
  243. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  244. $loader->load('services10.xml');
  245. $services = $container->findTaggedServiceIds('foo_tag');
  246. $this->assertCount(1, $services);
  247. foreach ($services as $id => $tagAttributes) {
  248. foreach ($tagAttributes as $attributes) {
  249. $this->assertArrayHasKey('other_option', $attributes);
  250. $this->assertEquals('lorem', $attributes['other_option']);
  251. $this->assertArrayHasKey('other-option', $attributes, 'unnormalized tag attributes should not be removed');
  252. $this->assertEquals('ciz', $attributes['some_option'], 'no overriding should be done when normalizing');
  253. $this->assertEquals('cat', $attributes['some-option']);
  254. $this->assertArrayNotHasKey('an_other_option', $attributes, 'normalization should not be done when an underscore is already found');
  255. }
  256. }
  257. }
  258. /**
  259. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  260. */
  261. public function testParseTagsWithoutNameThrowsException()
  262. {
  263. $container = new ContainerBuilder();
  264. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  265. $loader->load('tag_without_name.xml');
  266. }
  267. /**
  268. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  269. * @expectedExceptionMessageRegExp /The tag name for service ".+" in .* must be a non-empty string/
  270. */
  271. public function testParseTagWithEmptyNameThrowsException()
  272. {
  273. $container = new ContainerBuilder();
  274. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  275. $loader->load('tag_with_empty_name.xml');
  276. }
  277. public function testDeprecated()
  278. {
  279. $container = new ContainerBuilder();
  280. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  281. $loader->load('services_deprecated.xml');
  282. $this->assertTrue($container->getDefinition('foo')->isDeprecated());
  283. $message = 'The "foo" service is deprecated. You should stop using it, as it will soon be removed.';
  284. $this->assertSame($message, $container->getDefinition('foo')->getDeprecationMessage('foo'));
  285. $this->assertTrue($container->getDefinition('bar')->isDeprecated());
  286. $message = 'The "bar" service is deprecated.';
  287. $this->assertSame($message, $container->getDefinition('bar')->getDeprecationMessage('bar'));
  288. }
  289. public function testConvertDomElementToArray()
  290. {
  291. $doc = new \DOMDocument('1.0');
  292. $doc->loadXML('<foo>bar</foo>');
  293. $this->assertEquals('bar', XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
  294. $doc = new \DOMDocument('1.0');
  295. $doc->loadXML('<foo foo="bar" />');
  296. $this->assertEquals(array('foo' => 'bar'), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
  297. $doc = new \DOMDocument('1.0');
  298. $doc->loadXML('<foo><foo>bar</foo></foo>');
  299. $this->assertEquals(array('foo' => 'bar'), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
  300. $doc = new \DOMDocument('1.0');
  301. $doc->loadXML('<foo><foo>bar<foo>bar</foo></foo></foo>');
  302. $this->assertEquals(array('foo' => array('value' => 'bar', 'foo' => 'bar')), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
  303. $doc = new \DOMDocument('1.0');
  304. $doc->loadXML('<foo><foo></foo></foo>');
  305. $this->assertEquals(array('foo' => null), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
  306. $doc = new \DOMDocument('1.0');
  307. $doc->loadXML('<foo><foo><!-- foo --></foo></foo>');
  308. $this->assertEquals(array('foo' => null), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
  309. $doc = new \DOMDocument('1.0');
  310. $doc->loadXML('<foo><foo foo="bar"/><foo foo="bar"/></foo>');
  311. $this->assertEquals(array('foo' => array(array('foo' => 'bar'), array('foo' => 'bar'))), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
  312. }
  313. public function testExtensions()
  314. {
  315. $container = new ContainerBuilder();
  316. $container->registerExtension(new \ProjectExtension());
  317. $container->registerExtension(new \ProjectWithXsdExtension());
  318. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  319. // extension without an XSD
  320. $loader->load('extensions/services1.xml');
  321. $container->compile();
  322. $services = $container->getDefinitions();
  323. $parameters = $container->getParameterBag()->all();
  324. $this->assertArrayHasKey('project.service.bar', $services, '->load() parses extension elements');
  325. $this->assertArrayHasKey('project.parameter.bar', $parameters, '->load() parses extension elements');
  326. $this->assertEquals('BAR', $services['project.service.foo']->getClass(), '->load() parses extension elements');
  327. $this->assertEquals('BAR', $parameters['project.parameter.foo'], '->load() parses extension elements');
  328. // extension with an XSD
  329. $container = new ContainerBuilder();
  330. $container->registerExtension(new \ProjectExtension());
  331. $container->registerExtension(new \ProjectWithXsdExtension());
  332. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  333. $loader->load('extensions/services2.xml');
  334. $container->compile();
  335. $services = $container->getDefinitions();
  336. $parameters = $container->getParameterBag()->all();
  337. $this->assertArrayHasKey('project.service.bar', $services, '->load() parses extension elements');
  338. $this->assertArrayHasKey('project.parameter.bar', $parameters, '->load() parses extension elements');
  339. $this->assertEquals('BAR', $services['project.service.foo']->getClass(), '->load() parses extension elements');
  340. $this->assertEquals('BAR', $parameters['project.parameter.foo'], '->load() parses extension elements');
  341. $container = new ContainerBuilder();
  342. $container->registerExtension(new \ProjectExtension());
  343. $container->registerExtension(new \ProjectWithXsdExtension());
  344. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  345. // extension with an XSD (does not validate)
  346. try {
  347. $loader->load('extensions/services3.xml');
  348. $this->fail('->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
  349. } catch (\Exception $e) {
  350. $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
  351. $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'services3.xml'), $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
  352. $e = $e->getPrevious();
  353. $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
  354. $this->assertContains('The attribute \'bar\' is not allowed', $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
  355. }
  356. // non-registered extension
  357. try {
  358. $loader->load('extensions/services4.xml');
  359. $this->fail('->load() throws an InvalidArgumentException if the tag is not valid');
  360. } catch (\Exception $e) {
  361. $this->assertInstanceOf('\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the tag is not valid');
  362. $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');
  363. }
  364. }
  365. public function testExtensionInPhar()
  366. {
  367. if (extension_loaded('suhosin') && false === strpos(ini_get('suhosin.executor.include.whitelist'), 'phar')) {
  368. $this->markTestSkipped('To run this test, add "phar" to the "suhosin.executor.include.whitelist" settings in your php.ini file.');
  369. }
  370. if (defined('HHVM_VERSION')) {
  371. $this->markTestSkipped('HHVM makes this test conflict with those run in separate processes.');
  372. }
  373. require_once self::$fixturesPath.'/includes/ProjectWithXsdExtensionInPhar.phar';
  374. // extension with an XSD in PHAR archive
  375. $container = new ContainerBuilder();
  376. $container->registerExtension(new \ProjectWithXsdExtensionInPhar());
  377. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  378. $loader->load('extensions/services6.xml');
  379. // extension with an XSD in PHAR archive (does not validate)
  380. try {
  381. $loader->load('extensions/services7.xml');
  382. $this->fail('->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
  383. } catch (\Exception $e) {
  384. $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
  385. $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'services7.xml'), $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
  386. $e = $e->getPrevious();
  387. $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
  388. $this->assertContains('The attribute \'bar\' is not allowed', $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
  389. }
  390. }
  391. public function testSupports()
  392. {
  393. $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator());
  394. $this->assertTrue($loader->supports('foo.xml'), '->supports() returns true if the resource is loadable');
  395. $this->assertFalse($loader->supports('foo.foo'), '->supports() returns false if the resource is not loadable');
  396. $this->assertTrue($loader->supports('with_wrong_ext.yml', 'xml'), '->supports() returns true if the resource with forced type is loadable');
  397. }
  398. public function testNoNamingConflictsForAnonymousServices()
  399. {
  400. $container = new ContainerBuilder();
  401. $loader1 = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml/extension1'));
  402. $loader1->load('services.xml');
  403. $services = $container->getDefinitions();
  404. $this->assertCount(3, $services, '->load() attributes unique ids to anonymous services');
  405. $loader2 = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml/extension2'));
  406. $loader2->load('services.xml');
  407. $services = $container->getDefinitions();
  408. $this->assertCount(5, $services, '->load() attributes unique ids to anonymous services');
  409. $services = $container->getDefinitions();
  410. $args1 = $services['extension1.foo']->getArguments();
  411. $inner1 = $services[(string) $args1[0]];
  412. $this->assertEquals('BarClass1', $inner1->getClass(), '->load() uses the same configuration as for the anonymous ones');
  413. $args2 = $services['extension2.foo']->getArguments();
  414. $inner2 = $services[(string) $args2[0]];
  415. $this->assertEquals('BarClass2', $inner2->getClass(), '->load() uses the same configuration as for the anonymous ones');
  416. }
  417. public function testDocTypeIsNotAllowed()
  418. {
  419. $container = new ContainerBuilder();
  420. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  421. // document types are not allowed.
  422. try {
  423. $loader->load('withdoctype.xml');
  424. $this->fail('->load() throws an InvalidArgumentException if the configuration contains a document type');
  425. } catch (\Exception $e) {
  426. $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration contains a document type');
  427. $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'withdoctype.xml'), $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration contains a document type');
  428. $e = $e->getPrevious();
  429. $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration contains a document type');
  430. $this->assertSame('Document types are not allowed.', $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration contains a document type');
  431. }
  432. }
  433. public function testXmlNamespaces()
  434. {
  435. $container = new ContainerBuilder();
  436. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  437. $loader->load('namespaces.xml');
  438. $services = $container->getDefinitions();
  439. $this->assertArrayHasKey('foo', $services, '->load() parses <srv:service> elements');
  440. $this->assertCount(1, $services['foo']->getTag('foo.tag'), '->load parses <srv:tag> elements');
  441. $this->assertEquals(array(array('setBar', array('foo'))), $services['foo']->getMethodCalls(), '->load() parses the <srv:call> tag');
  442. }
  443. public function testLoadIndexedArguments()
  444. {
  445. $container = new ContainerBuilder();
  446. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  447. $loader->load('services14.xml');
  448. $this->assertEquals(array('index_0' => 'app'), $container->findDefinition('logger')->getArguments());
  449. }
  450. public function testLoadInlinedServices()
  451. {
  452. $container = new ContainerBuilder();
  453. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  454. $loader->load('services21.xml');
  455. $foo = $container->getDefinition('foo');
  456. $fooFactory = $foo->getFactory();
  457. $this->assertInstanceOf(Reference::class, $fooFactory[0]);
  458. $this->assertTrue($container->has((string) $fooFactory[0]));
  459. $fooFactoryDefinition = $container->getDefinition((string) $fooFactory[0]);
  460. $this->assertSame('FooFactory', $fooFactoryDefinition->getClass());
  461. $this->assertSame('createFoo', $fooFactory[1]);
  462. $fooFactoryFactory = $fooFactoryDefinition->getFactory();
  463. $this->assertInstanceOf(Reference::class, $fooFactoryFactory[0]);
  464. $this->assertTrue($container->has((string) $fooFactoryFactory[0]));
  465. $this->assertSame('Foobar', $container->getDefinition((string) $fooFactoryFactory[0])->getClass());
  466. $this->assertSame('createFooFactory', $fooFactoryFactory[1]);
  467. $fooConfigurator = $foo->getConfigurator();
  468. $this->assertInstanceOf(Reference::class, $fooConfigurator[0]);
  469. $this->assertTrue($container->has((string) $fooConfigurator[0]));
  470. $fooConfiguratorDefinition = $container->getDefinition((string) $fooConfigurator[0]);
  471. $this->assertSame('Bar', $fooConfiguratorDefinition->getClass());
  472. $this->assertSame('configureFoo', $fooConfigurator[1]);
  473. $barConfigurator = $fooConfiguratorDefinition->getConfigurator();
  474. $this->assertInstanceOf(Reference::class, $barConfigurator[0]);
  475. $this->assertSame('Baz', $container->getDefinition((string) $barConfigurator[0])->getClass());
  476. $this->assertSame('configureBar', $barConfigurator[1]);
  477. }
  478. /**
  479. * @group legacy
  480. */
  481. public function testType()
  482. {
  483. $container = new ContainerBuilder();
  484. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  485. $loader->load('services22.xml');
  486. $this->assertEquals(array('Bar', 'Baz'), $container->getDefinition('foo')->getAutowiringTypes());
  487. }
  488. public function testAutowire()
  489. {
  490. $container = new ContainerBuilder();
  491. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  492. $loader->load('services23.xml');
  493. $this->assertTrue($container->getDefinition('bar')->isAutowired());
  494. }
  495. public function testClassFromId()
  496. {
  497. $container = new ContainerBuilder();
  498. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  499. $loader->load('class_from_id.xml');
  500. $container->compile();
  501. $this->assertEquals(CaseSensitiveClass::class, $container->getDefinition(CaseSensitiveClass::class)->getClass());
  502. }
  503. public function testPrototype()
  504. {
  505. $container = new ContainerBuilder();
  506. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  507. $loader->load('services_prototype.xml');
  508. $ids = array_keys($container->getDefinitions());
  509. sort($ids);
  510. $this->assertSame(array(Prototype\Foo::class, Prototype\Sub\Bar::class, 'service_container'), $ids);
  511. $resources = $container->getResources();
  512. $fixturesDir = dirname(__DIR__).DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR;
  513. $this->assertTrue(false !== array_search(new FileResource($fixturesDir.'xml'.DIRECTORY_SEPARATOR.'services_prototype.xml'), $resources));
  514. $this->assertTrue(false !== array_search(new GlobResource($fixturesDir.'Prototype', '/*', true), $resources));
  515. $resources = array_map('strval', $resources);
  516. $this->assertContains('reflection.Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Foo', $resources);
  517. $this->assertContains('reflection.Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Sub\Bar', $resources);
  518. }
  519. /**
  520. * @group legacy
  521. * @expectedDeprecation Using the attribute "class" is deprecated for the service "bar" which is defined as an alias %s.
  522. * @expectedDeprecation Using the element "tag" is deprecated for the service "bar" which is defined as an alias %s.
  523. * @expectedDeprecation Using the element "factory" is deprecated for the service "bar" which is defined as an alias %s.
  524. */
  525. public function testAliasDefinitionContainsUnsupportedElements()
  526. {
  527. $container = new ContainerBuilder();
  528. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  529. $loader->load('legacy_invalid_alias_definition.xml');
  530. $this->assertTrue($container->has('bar'));
  531. }
  532. public function testArgumentWithKeyOutsideCollection()
  533. {
  534. $container = new ContainerBuilder();
  535. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  536. $loader->load('with_key_outside_collection.xml');
  537. $this->assertSame(array('type' => 'foo', 'bar'), $container->getDefinition('foo')->getArguments());
  538. }
  539. public function testDefaults()
  540. {
  541. $container = new ContainerBuilder();
  542. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  543. $loader->load('services28.xml');
  544. $this->assertFalse($container->getDefinition('with_defaults')->isPublic());
  545. $this->assertSame(array('foo' => array(array())), $container->getDefinition('with_defaults')->getTags());
  546. $this->assertTrue($container->getDefinition('with_defaults')->isAutowired());
  547. $this->assertArrayNotHasKey('public', $container->getDefinition('with_defaults')->getChanges());
  548. $this->assertArrayNotHasKey('autowire', $container->getDefinition('with_defaults')->getChanges());
  549. $container->compile();
  550. $this->assertTrue($container->getDefinition('no_defaults')->isPublic());
  551. $this->assertSame(array('foo' => array(array())), $container->getDefinition('no_defaults')->getTags());
  552. $this->assertFalse($container->getDefinition('no_defaults')->isAutowired());
  553. $this->assertTrue($container->getDefinition('child_def')->isPublic());
  554. $this->assertSame(array('foo' => array(array())), $container->getDefinition('child_def')->getTags());
  555. $this->assertFalse($container->getDefinition('child_def')->isAutowired());
  556. $definitions = $container->getDefinitions();
  557. $this->assertSame('service_container', key($definitions));
  558. array_shift($definitions);
  559. $this->assertStringStartsWith('1_', key($definitions));
  560. $anonymous = current($definitions);
  561. $this->assertTrue($anonymous->isPublic());
  562. $this->assertTrue($anonymous->isAutowired());
  563. $this->assertSame(array('foo' => array(array())), $anonymous->getTags());
  564. }
  565. public function testNamedArguments()
  566. {
  567. $container = new ContainerBuilder();
  568. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  569. $loader->load('services_named_args.xml');
  570. $this->assertEquals(array(null, '$apiKey' => 'ABCD'), $container->getDefinition(NamedArgumentsDummy::class)->getArguments());
  571. $container->compile();
  572. $this->assertEquals(array(null, 'ABCD'), $container->getDefinition(NamedArgumentsDummy::class)->getArguments());
  573. $this->assertEquals(array(array('setApiKey', array('123'))), $container->getDefinition(NamedArgumentsDummy::class)->getMethodCalls());
  574. }
  575. public function testInstanceof()
  576. {
  577. $container = new ContainerBuilder();
  578. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  579. $loader->load('services_instanceof.xml');
  580. $container->compile();
  581. $definition = $container->getDefinition(Bar::class);
  582. $this->assertTrue($definition->isAutowired());
  583. $this->assertTrue($definition->isLazy());
  584. $this->assertSame(array('foo' => array(array()), 'bar' => array(array())), $definition->getTags());
  585. }
  586. /**
  587. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  588. * @expectedExceptionMessage The service "child_service" cannot use the "parent" option in the same file where "instanceof" configuration is defined as using both is not supported. Move your child definitions to a separate file.
  589. */
  590. public function testInstanceOfAndChildDefinitionNotAllowed()
  591. {
  592. $container = new ContainerBuilder();
  593. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  594. $loader->load('services_instanceof_with_parent.xml');
  595. $container->compile();
  596. }
  597. /**
  598. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  599. * @expectedExceptionMessage The service "child_service" cannot have a "parent" and also have "autoconfigure". Try setting autoconfigure="false" for the service.
  600. */
  601. public function testAutoConfigureAndChildDefinitionNotAllowed()
  602. {
  603. $container = new ContainerBuilder();
  604. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  605. $loader->load('services_autoconfigure_with_parent.xml');
  606. $container->compile();
  607. }
  608. /**
  609. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  610. * @expectedExceptionMessage Attribute "autowire" on service "child_service" cannot be inherited from "defaults" when a "parent" is set. Move your child definitions to a separate file or define this attribute explicitly.
  611. */
  612. public function testDefaultsAndChildDefinitionNotAllowed()
  613. {
  614. $container = new ContainerBuilder();
  615. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  616. $loader->load('services_defaults_with_parent.xml');
  617. $container->compile();
  618. }
  619. public function testAutoConfigureInstanceof()
  620. {
  621. $container = new ContainerBuilder();
  622. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  623. $loader->load('services_autoconfigure.xml');
  624. $this->assertTrue($container->getDefinition('use_defaults_settings')->isAutoconfigured());
  625. $this->assertFalse($container->getDefinition('override_defaults_settings_to_false')->isAutoconfigured());
  626. }
  627. }
  628. interface BarInterface
  629. {
  630. }
  631. class Bar implements BarInterface
  632. {
  633. }