4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\DependencyInjection\Tests\Loader;
14 use PHPUnit\Framework\TestCase;
15 use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
16 use Symfony\Component\DependencyInjection\ContainerBuilder;
17 use Symfony\Component\DependencyInjection\Reference;
18 use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
19 use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
20 use Symfony\Component\DependencyInjection\Loader\IniFileLoader;
21 use Symfony\Component\Config\Loader\LoaderResolver;
22 use Symfony\Component\Config\FileLocator;
23 use Symfony\Component\Config\Resource\FileResource;
24 use Symfony\Component\Config\Resource\GlobResource;
25 use Symfony\Component\DependencyInjection\Tests\Fixtures\Bar;
26 use Symfony\Component\DependencyInjection\Tests\Fixtures\BarInterface;
27 use Symfony\Component\DependencyInjection\Tests\Fixtures\CaseSensitiveClass;
28 use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype;
29 use Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy;
30 use Symfony\Component\ExpressionLanguage\Expression;
32 class XmlFileLoaderTest extends TestCase
34 protected static $fixturesPath;
36 public static function setUpBeforeClass()
38 self::$fixturesPath = realpath(__DIR__.'/../Fixtures/');
39 require_once self::$fixturesPath.'/includes/foo.php';
40 require_once self::$fixturesPath.'/includes/ProjectExtension.php';
41 require_once self::$fixturesPath.'/includes/ProjectWithXsdExtension.php';
44 public function testLoad()
46 $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/ini'));
49 $loader->load('foo.xml');
50 $this->fail('->load() throws an InvalidArgumentException if the loaded file does not exist');
51 } catch (\Exception $e) {
52 $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the loaded file does not exist');
53 $this->assertStringStartsWith('The file "foo.xml" does not exist (in:', $e->getMessage(), '->load() throws an InvalidArgumentException if the loaded file does not exist');
57 public function testParseFile()
59 $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/ini'));
60 $r = new \ReflectionObject($loader);
61 $m = $r->getMethod('parseFileToDOM');
62 $m->setAccessible(true);
65 $m->invoke($loader, self::$fixturesPath.'/ini/parameters.ini');
66 $this->fail('->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file');
67 } catch (\Exception $e) {
68 $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file');
69 $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');
71 $e = $e->getPrevious();
72 $this->assertInstanceOf('InvalidArgumentException', $e, '->parseFileToDOM() throws an InvalidArgumentException if the loaded file is not a valid XML file');
73 $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');
76 $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/xml'));
79 $m->invoke($loader, self::$fixturesPath.'/xml/nonvalid.xml');
80 $this->fail('->parseFileToDOM() throws an InvalidArgumentException if the loaded file does not validate the XSD');
81 } catch (\Exception $e) {
82 $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->parseFileToDOM() throws an InvalidArgumentException if the loaded file does not validate the XSD');
83 $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');
85 $e = $e->getPrevious();
86 $this->assertInstanceOf('InvalidArgumentException', $e, '->parseFileToDOM() throws an InvalidArgumentException if the loaded file does not validate the XSD');
87 $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');
90 $xml = $m->invoke($loader, self::$fixturesPath.'/xml/services1.xml');
91 $this->assertInstanceOf('DOMDocument', $xml, '->parseFileToDOM() returns an SimpleXMLElement object');
94 public function testLoadWithExternalEntitiesDisabled()
96 $disableEntities = libxml_disable_entity_loader(true);
98 $containerBuilder = new ContainerBuilder();
99 $loader = new XmlFileLoader($containerBuilder, new FileLocator(self::$fixturesPath.'/xml'));
100 $loader->load('services2.xml');
102 libxml_disable_entity_loader($disableEntities);
104 $this->assertGreaterThan(0, $containerBuilder->getParameterBag()->all(), 'Parameters can be read from the config file.');
107 public function testLoadParameters()
109 $container = new ContainerBuilder();
110 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
111 $loader->load('services2.xml');
113 $actual = $container->getParameterBag()->all();
131 'mixedcase' => array('MixedCaseKey' => 'value'),
132 'constant' => PHP_EOL,
135 $this->assertEquals($expected, $actual, '->load() converts XML values to PHP ones');
138 public function testLoadImports()
140 $container = new ContainerBuilder();
141 $resolver = new LoaderResolver(array(
142 new IniFileLoader($container, new FileLocator(self::$fixturesPath.'/ini')),
143 new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yml')),
144 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')),
146 $loader->setResolver($resolver);
147 $loader->load('services4.xml');
149 $actual = $container->getParameterBag()->all();
167 'mixedcase' => array('MixedCaseKey' => 'value'),
168 'constant' => PHP_EOL,
170 'imported_from_ini' => true,
171 'imported_from_yaml' => true,
172 'with_wrong_ext' => 'from yaml',
175 $this->assertEquals(array_keys($expected), array_keys($actual), '->load() imports and merges imported files');
176 $this->assertTrue($actual['imported_from_ini']);
178 // Bad import throws no exception due to ignore_errors value.
179 $loader->load('services4_bad_import.xml');
182 public function testLoadAnonymousServices()
184 $container = new ContainerBuilder();
185 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
186 $loader->load('services5.xml');
187 $services = $container->getDefinitions();
188 $this->assertCount(7, $services, '->load() attributes unique ids to anonymous services');
190 // anonymous service as an argument
191 $args = $services['foo']->getArguments();
192 $this->assertCount(1, $args, '->load() references anonymous services as "normal" ones');
193 $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Reference', $args[0], '->load() converts anonymous services to references to "normal" services');
194 $this->assertArrayHasKey((string) $args[0], $services, '->load() makes a reference to the created ones');
195 $inner = $services[(string) $args[0]];
196 $this->assertEquals('BarClass', $inner->getClass(), '->load() uses the same configuration as for the anonymous ones');
197 $this->assertFalse($inner->isPublic());
199 // inner anonymous services
200 $args = $inner->getArguments();
201 $this->assertCount(1, $args, '->load() references anonymous services as "normal" ones');
202 $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Reference', $args[0], '->load() converts anonymous services to references to "normal" services');
203 $this->assertArrayHasKey((string) $args[0], $services, '->load() makes a reference to the created ones');
204 $inner = $services[(string) $args[0]];
205 $this->assertEquals('BazClass', $inner->getClass(), '->load() uses the same configuration as for the anonymous ones');
206 $this->assertFalse($inner->isPublic());
208 // anonymous service as a property
209 $properties = $services['foo']->getProperties();
210 $property = $properties['p'];
211 $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Reference', $property, '->load() converts anonymous services to references to "normal" services');
212 $this->assertArrayHasKey((string) $property, $services, '->load() makes a reference to the created ones');
213 $inner = $services[(string) $property];
214 $this->assertEquals('BuzClass', $inner->getClass(), '->load() uses the same configuration as for the anonymous ones');
215 $this->assertFalse($inner->isPublic());
218 $service = $container->findTaggedServiceIds('biz_tag');
219 $this->assertCount(1, $service);
221 foreach ($service as $id => $tag) {
222 $service = $container->getDefinition($id);
224 $this->assertEquals('BizClass', $service->getClass(), '->load() uses the same configuration as for the anonymous ones');
225 $this->assertTrue($service->isPublic());
227 // anonymous services are shared when using decoration definitions
228 $container->compile();
229 $services = $container->getDefinitions();
230 $fooArgs = $services['foo']->getArguments();
231 $barArgs = $services['bar']->getArguments();
232 $this->assertSame($fooArgs[0], $barArgs[0]);
237 * @expectedDeprecation Top-level anonymous services are deprecated since Symfony 3.4, the "id" attribute will be required in version 4.0 in %sservices_without_id.xml at line 5.
239 public function testLoadAnonymousServicesWithoutId()
241 $container = new ContainerBuilder();
242 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
243 $loader->load('services_without_id.xml');
246 public function testLoadAnonymousNestedServices()
248 $container = new ContainerBuilder();
249 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
250 $loader->load('nested_service_without_id.xml');
252 $this->assertTrue($container->hasDefinition('FooClass'));
253 $arguments = $container->getDefinition('FooClass')->getArguments();
254 $this->assertInstanceOf(Reference::class, array_shift($arguments));
257 public function testLoadServices()
259 $container = new ContainerBuilder();
260 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
261 $loader->load('services6.xml');
262 $services = $container->getDefinitions();
263 $this->assertArrayHasKey('foo', $services, '->load() parses <service> elements');
264 $this->assertFalse($services['not_shared']->isShared(), '->load() parses shared flag');
265 $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Definition', $services['foo'], '->load() converts <service> element to Definition instances');
266 $this->assertEquals('FooClass', $services['foo']->getClass(), '->load() parses the class attribute');
267 $this->assertEquals('%path%/foo.php', $services['file']->getFile(), '->load() parses the file tag');
268 $this->assertEquals(array('foo', new Reference('foo'), array(true, false)), $services['arguments']->getArguments(), '->load() parses the argument tags');
269 $this->assertEquals('sc_configure', $services['configurator1']->getConfigurator(), '->load() parses the configurator tag');
270 $this->assertEquals(array(new Reference('baz'), 'configure'), $services['configurator2']->getConfigurator(), '->load() parses the configurator tag');
271 $this->assertEquals(array('BazClass', 'configureStatic'), $services['configurator3']->getConfigurator(), '->load() parses the configurator tag');
272 $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');
273 $this->assertEquals(array(array('setBar', array('foo', new Reference('foo'), array(true, false)))), $services['method_call2']->getMethodCalls(), '->load() parses the method_call tag');
274 $this->assertEquals('factory', $services['new_factory1']->getFactory(), '->load() parses the factory tag');
275 $this->assertEquals(array(new Reference('baz'), 'getClass'), $services['new_factory2']->getFactory(), '->load() parses the factory tag');
276 $this->assertEquals(array('BazClass', 'getInstance'), $services['new_factory3']->getFactory(), '->load() parses the factory tag');
277 $this->assertSame(array(null, 'getInstance'), $services['new_factory4']->getFactory(), '->load() accepts factory tag without class');
279 $aliases = $container->getAliases();
280 $this->assertArrayHasKey('alias_for_foo', $aliases, '->load() parses <service> elements');
281 $this->assertEquals('foo', (string) $aliases['alias_for_foo'], '->load() parses aliases');
282 $this->assertTrue($aliases['alias_for_foo']->isPublic());
283 $this->assertArrayHasKey('another_alias_for_foo', $aliases);
284 $this->assertEquals('foo', (string) $aliases['another_alias_for_foo']);
285 $this->assertFalse($aliases['another_alias_for_foo']->isPublic());
287 $this->assertEquals(array('decorated', null, 0), $services['decorator_service']->getDecoratedService());
288 $this->assertEquals(array('decorated', 'decorated.pif-pouf', 0), $services['decorator_service_with_name']->getDecoratedService());
289 $this->assertEquals(array('decorated', 'decorated.pif-pouf', 5), $services['decorator_service_with_name_and_priority']->getDecoratedService());
292 public function testParsesIteratorArgument()
294 $container = new ContainerBuilder();
295 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
296 $loader->load('services9.xml');
298 $lazyDefinition = $container->getDefinition('lazy_context');
300 $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');
303 public function testParsesTags()
305 $container = new ContainerBuilder();
306 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
307 $loader->load('services10.xml');
309 $services = $container->findTaggedServiceIds('foo_tag');
310 $this->assertCount(1, $services);
312 foreach ($services as $id => $tagAttributes) {
313 foreach ($tagAttributes as $attributes) {
314 $this->assertArrayHasKey('other_option', $attributes);
315 $this->assertEquals('lorem', $attributes['other_option']);
316 $this->assertArrayHasKey('other-option', $attributes, 'unnormalized tag attributes should not be removed');
318 $this->assertEquals('ciz', $attributes['some_option'], 'no overriding should be done when normalizing');
319 $this->assertEquals('cat', $attributes['some-option']);
321 $this->assertArrayNotHasKey('an_other_option', $attributes, 'normalization should not be done when an underscore is already found');
327 * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
329 public function testParseTagsWithoutNameThrowsException()
331 $container = new ContainerBuilder();
332 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
333 $loader->load('tag_without_name.xml');
337 * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
338 * @expectedExceptionMessageRegExp /The tag name for service ".+" in .* must be a non-empty string/
340 public function testParseTagWithEmptyNameThrowsException()
342 $container = new ContainerBuilder();
343 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
344 $loader->load('tag_with_empty_name.xml');
347 public function testDeprecated()
349 $container = new ContainerBuilder();
350 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
351 $loader->load('services_deprecated.xml');
353 $this->assertTrue($container->getDefinition('foo')->isDeprecated());
354 $message = 'The "foo" service is deprecated. You should stop using it, as it will soon be removed.';
355 $this->assertSame($message, $container->getDefinition('foo')->getDeprecationMessage('foo'));
357 $this->assertTrue($container->getDefinition('bar')->isDeprecated());
358 $message = 'The "bar" service is deprecated.';
359 $this->assertSame($message, $container->getDefinition('bar')->getDeprecationMessage('bar'));
362 public function testConvertDomElementToArray()
364 $doc = new \DOMDocument('1.0');
365 $doc->loadXML('<foo>bar</foo>');
366 $this->assertEquals('bar', XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
368 $doc = new \DOMDocument('1.0');
369 $doc->loadXML('<foo foo="bar" />');
370 $this->assertEquals(array('foo' => 'bar'), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
372 $doc = new \DOMDocument('1.0');
373 $doc->loadXML('<foo><foo>bar</foo></foo>');
374 $this->assertEquals(array('foo' => 'bar'), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
376 $doc = new \DOMDocument('1.0');
377 $doc->loadXML('<foo><foo>bar<foo>bar</foo></foo></foo>');
378 $this->assertEquals(array('foo' => array('value' => 'bar', 'foo' => 'bar')), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
380 $doc = new \DOMDocument('1.0');
381 $doc->loadXML('<foo><foo></foo></foo>');
382 $this->assertEquals(array('foo' => null), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
384 $doc = new \DOMDocument('1.0');
385 $doc->loadXML('<foo><foo><!-- foo --></foo></foo>');
386 $this->assertEquals(array('foo' => null), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
388 $doc = new \DOMDocument('1.0');
389 $doc->loadXML('<foo><foo foo="bar"/><foo foo="bar"/></foo>');
390 $this->assertEquals(array('foo' => array(array('foo' => 'bar'), array('foo' => 'bar'))), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
393 public function testExtensions()
395 $container = new ContainerBuilder();
396 $container->registerExtension(new \ProjectExtension());
397 $container->registerExtension(new \ProjectWithXsdExtension());
398 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
400 // extension without an XSD
401 $loader->load('extensions/services1.xml');
402 $container->compile();
403 $services = $container->getDefinitions();
404 $parameters = $container->getParameterBag()->all();
406 $this->assertArrayHasKey('project.service.bar', $services, '->load() parses extension elements');
407 $this->assertArrayHasKey('project.parameter.bar', $parameters, '->load() parses extension elements');
409 $this->assertEquals('BAR', $services['project.service.foo']->getClass(), '->load() parses extension elements');
410 $this->assertEquals('BAR', $parameters['project.parameter.foo'], '->load() parses extension elements');
412 // extension with an XSD
413 $container = new ContainerBuilder();
414 $container->registerExtension(new \ProjectExtension());
415 $container->registerExtension(new \ProjectWithXsdExtension());
416 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
417 $loader->load('extensions/services2.xml');
418 $container->compile();
419 $services = $container->getDefinitions();
420 $parameters = $container->getParameterBag()->all();
422 $this->assertArrayHasKey('project.service.bar', $services, '->load() parses extension elements');
423 $this->assertArrayHasKey('project.parameter.bar', $parameters, '->load() parses extension elements');
425 $this->assertEquals('BAR', $services['project.service.foo']->getClass(), '->load() parses extension elements');
426 $this->assertEquals('BAR', $parameters['project.parameter.foo'], '->load() parses extension elements');
428 $container = new ContainerBuilder();
429 $container->registerExtension(new \ProjectExtension());
430 $container->registerExtension(new \ProjectWithXsdExtension());
431 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
433 // extension with an XSD (does not validate)
435 $loader->load('extensions/services3.xml');
436 $this->fail('->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
437 } catch (\Exception $e) {
438 $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
439 $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'services3.xml'), $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
441 $e = $e->getPrevious();
442 $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
443 $this->assertContains('The attribute \'bar\' is not allowed', $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
446 // non-registered extension
448 $loader->load('extensions/services4.xml');
449 $this->fail('->load() throws an InvalidArgumentException if the tag is not valid');
450 } catch (\Exception $e) {
451 $this->assertInstanceOf('\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the tag is not valid');
452 $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');
456 public function testExtensionInPhar()
458 if (extension_loaded('suhosin') && false === strpos(ini_get('suhosin.executor.include.whitelist'), 'phar')) {
459 $this->markTestSkipped('To run this test, add "phar" to the "suhosin.executor.include.whitelist" settings in your php.ini file.');
461 if (defined('HHVM_VERSION')) {
462 $this->markTestSkipped('HHVM makes this test conflict with those run in separate processes.');
465 require_once self::$fixturesPath.'/includes/ProjectWithXsdExtensionInPhar.phar';
467 // extension with an XSD in PHAR archive
468 $container = new ContainerBuilder();
469 $container->registerExtension(new \ProjectWithXsdExtensionInPhar());
470 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
471 $loader->load('extensions/services6.xml');
473 // extension with an XSD in PHAR archive (does not validate)
475 $loader->load('extensions/services7.xml');
476 $this->fail('->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
477 } catch (\Exception $e) {
478 $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
479 $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'services7.xml'), $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
481 $e = $e->getPrevious();
482 $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
483 $this->assertContains('The attribute \'bar\' is not allowed', $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
487 public function testSupports()
489 $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator());
491 $this->assertTrue($loader->supports('foo.xml'), '->supports() returns true if the resource is loadable');
492 $this->assertFalse($loader->supports('foo.foo'), '->supports() returns false if the resource is not loadable');
493 $this->assertTrue($loader->supports('with_wrong_ext.yml', 'xml'), '->supports() returns true if the resource with forced type is loadable');
496 public function testNoNamingConflictsForAnonymousServices()
498 $container = new ContainerBuilder();
500 $loader1 = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml/extension1'));
501 $loader1->load('services.xml');
502 $services = $container->getDefinitions();
503 $this->assertCount(3, $services, '->load() attributes unique ids to anonymous services');
504 $loader2 = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml/extension2'));
505 $loader2->load('services.xml');
506 $services = $container->getDefinitions();
507 $this->assertCount(5, $services, '->load() attributes unique ids to anonymous services');
509 $services = $container->getDefinitions();
510 $args1 = $services['extension1.foo']->getArguments();
511 $inner1 = $services[(string) $args1[0]];
512 $this->assertEquals('BarClass1', $inner1->getClass(), '->load() uses the same configuration as for the anonymous ones');
513 $args2 = $services['extension2.foo']->getArguments();
514 $inner2 = $services[(string) $args2[0]];
515 $this->assertEquals('BarClass2', $inner2->getClass(), '->load() uses the same configuration as for the anonymous ones');
518 public function testDocTypeIsNotAllowed()
520 $container = new ContainerBuilder();
522 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
524 // document types are not allowed.
526 $loader->load('withdoctype.xml');
527 $this->fail('->load() throws an InvalidArgumentException if the configuration contains a document type');
528 } catch (\Exception $e) {
529 $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration contains a document type');
530 $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'withdoctype.xml'), $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration contains a document type');
532 $e = $e->getPrevious();
533 $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration contains a document type');
534 $this->assertSame('Document types are not allowed.', $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration contains a document type');
538 public function testXmlNamespaces()
540 $container = new ContainerBuilder();
541 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
542 $loader->load('namespaces.xml');
543 $services = $container->getDefinitions();
545 $this->assertArrayHasKey('foo', $services, '->load() parses <srv:service> elements');
546 $this->assertCount(1, $services['foo']->getTag('foo.tag'), '->load parses <srv:tag> elements');
547 $this->assertEquals(array(array('setBar', array('foo'))), $services['foo']->getMethodCalls(), '->load() parses the <srv:call> tag');
550 public function testLoadIndexedArguments()
552 $container = new ContainerBuilder();
553 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
554 $loader->load('services14.xml');
556 $this->assertEquals(array('index_0' => 'app'), $container->findDefinition('logger')->getArguments());
559 public function testLoadInlinedServices()
561 $container = new ContainerBuilder();
562 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
563 $loader->load('services21.xml');
565 $foo = $container->getDefinition('foo');
567 $fooFactory = $foo->getFactory();
568 $this->assertInstanceOf(Reference::class, $fooFactory[0]);
569 $this->assertTrue($container->has((string) $fooFactory[0]));
570 $fooFactoryDefinition = $container->getDefinition((string) $fooFactory[0]);
571 $this->assertSame('FooFactory', $fooFactoryDefinition->getClass());
572 $this->assertSame('createFoo', $fooFactory[1]);
574 $fooFactoryFactory = $fooFactoryDefinition->getFactory();
575 $this->assertInstanceOf(Reference::class, $fooFactoryFactory[0]);
576 $this->assertTrue($container->has((string) $fooFactoryFactory[0]));
577 $this->assertSame('Foobar', $container->getDefinition((string) $fooFactoryFactory[0])->getClass());
578 $this->assertSame('createFooFactory', $fooFactoryFactory[1]);
580 $fooConfigurator = $foo->getConfigurator();
581 $this->assertInstanceOf(Reference::class, $fooConfigurator[0]);
582 $this->assertTrue($container->has((string) $fooConfigurator[0]));
583 $fooConfiguratorDefinition = $container->getDefinition((string) $fooConfigurator[0]);
584 $this->assertSame('Bar', $fooConfiguratorDefinition->getClass());
585 $this->assertSame('configureFoo', $fooConfigurator[1]);
587 $barConfigurator = $fooConfiguratorDefinition->getConfigurator();
588 $this->assertInstanceOf(Reference::class, $barConfigurator[0]);
589 $this->assertSame('Baz', $container->getDefinition((string) $barConfigurator[0])->getClass());
590 $this->assertSame('configureBar', $barConfigurator[1]);
596 public function testType()
598 $container = new ContainerBuilder();
599 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
600 $loader->load('services22.xml');
602 $this->assertEquals(array('Bar', 'Baz'), $container->getDefinition('foo')->getAutowiringTypes());
605 public function testAutowire()
607 $container = new ContainerBuilder();
608 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
609 $loader->load('services23.xml');
611 $this->assertTrue($container->getDefinition('bar')->isAutowired());
614 public function testClassFromId()
616 $container = new ContainerBuilder();
617 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
618 $loader->load('class_from_id.xml');
619 $container->compile();
621 $this->assertEquals(CaseSensitiveClass::class, $container->getDefinition(CaseSensitiveClass::class)->getClass());
624 public function testPrototype()
626 $container = new ContainerBuilder();
627 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
628 $loader->load('services_prototype.xml');
630 $ids = array_keys($container->getDefinitions());
632 $this->assertSame(array(Prototype\Foo::class, Prototype\Sub\Bar::class, 'service_container'), $ids);
634 $resources = $container->getResources();
636 $fixturesDir = dirname(__DIR__).DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR;
637 $this->assertTrue(false !== array_search(new FileResource($fixturesDir.'xml'.DIRECTORY_SEPARATOR.'services_prototype.xml'), $resources));
638 $this->assertTrue(false !== array_search(new GlobResource($fixturesDir.'Prototype', '/*', true), $resources));
639 $resources = array_map('strval', $resources);
640 $this->assertContains('reflection.Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Foo', $resources);
641 $this->assertContains('reflection.Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Sub\Bar', $resources);
646 * @expectedDeprecation Using the attribute "class" is deprecated for the service "bar" which is defined as an alias %s.
647 * @expectedDeprecation Using the element "tag" is deprecated for the service "bar" which is defined as an alias %s.
648 * @expectedDeprecation Using the element "factory" is deprecated for the service "bar" which is defined as an alias %s.
650 public function testAliasDefinitionContainsUnsupportedElements()
652 $container = new ContainerBuilder();
653 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
655 $loader->load('legacy_invalid_alias_definition.xml');
657 $this->assertTrue($container->has('bar'));
660 public function testArgumentWithKeyOutsideCollection()
662 $container = new ContainerBuilder();
663 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
664 $loader->load('with_key_outside_collection.xml');
666 $this->assertSame(array('type' => 'foo', 'bar'), $container->getDefinition('foo')->getArguments());
669 public function testDefaults()
671 $container = new ContainerBuilder();
672 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
673 $loader->load('services28.xml');
675 $this->assertFalse($container->getDefinition('with_defaults')->isPublic());
676 $this->assertSame(array('foo' => array(array())), $container->getDefinition('with_defaults')->getTags());
677 $this->assertTrue($container->getDefinition('with_defaults')->isAutowired());
678 $this->assertArrayNotHasKey('public', $container->getDefinition('with_defaults')->getChanges());
679 $this->assertArrayNotHasKey('autowire', $container->getDefinition('with_defaults')->getChanges());
681 $container->compile();
683 $this->assertTrue($container->getDefinition('no_defaults')->isPublic());
685 $this->assertSame(array('foo' => array(array())), $container->getDefinition('no_defaults')->getTags());
687 $this->assertFalse($container->getDefinition('no_defaults')->isAutowired());
689 $this->assertTrue($container->getDefinition('child_def')->isPublic());
690 $this->assertSame(array('foo' => array(array())), $container->getDefinition('child_def')->getTags());
691 $this->assertFalse($container->getDefinition('child_def')->isAutowired());
693 $definitions = $container->getDefinitions();
694 $this->assertSame('service_container', key($definitions));
696 array_shift($definitions);
697 $anonymous = current($definitions);
698 $this->assertSame('bar', key($definitions));
699 $this->assertTrue($anonymous->isPublic());
700 $this->assertTrue($anonymous->isAutowired());
701 $this->assertSame(array('foo' => array(array())), $anonymous->getTags());
704 public function testNamedArguments()
706 $container = new ContainerBuilder();
707 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
708 $loader->load('services_named_args.xml');
710 $this->assertEquals(array('$apiKey' => 'ABCD', CaseSensitiveClass::class => null), $container->getDefinition(NamedArgumentsDummy::class)->getArguments());
712 $container->compile();
714 $this->assertEquals(array(null, 'ABCD'), $container->getDefinition(NamedArgumentsDummy::class)->getArguments());
715 $this->assertEquals(array(array('setApiKey', array('123'))), $container->getDefinition(NamedArgumentsDummy::class)->getMethodCalls());
718 public function testInstanceof()
720 $container = new ContainerBuilder();
721 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
722 $loader->load('services_instanceof.xml');
723 $container->compile();
725 $definition = $container->getDefinition(Bar::class);
726 $this->assertTrue($definition->isAutowired());
727 $this->assertTrue($definition->isLazy());
728 $this->assertSame(array('foo' => array(array()), 'bar' => array(array())), $definition->getTags());
732 * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
733 * @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.
735 public function testInstanceOfAndChildDefinitionNotAllowed()
737 $container = new ContainerBuilder();
738 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
739 $loader->load('services_instanceof_with_parent.xml');
740 $container->compile();
744 * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
745 * @expectedExceptionMessage The service "child_service" cannot have a "parent" and also have "autoconfigure". Try setting autoconfigure="false" for the service.
747 public function testAutoConfigureAndChildDefinitionNotAllowed()
749 $container = new ContainerBuilder();
750 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
751 $loader->load('services_autoconfigure_with_parent.xml');
752 $container->compile();
756 * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
757 * @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.
759 public function testDefaultsAndChildDefinitionNotAllowed()
761 $container = new ContainerBuilder();
762 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
763 $loader->load('services_defaults_with_parent.xml');
764 $container->compile();
767 public function testAutoConfigureInstanceof()
769 $container = new ContainerBuilder();
770 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
771 $loader->load('services_autoconfigure.xml');
773 $this->assertTrue($container->getDefinition('use_defaults_settings')->isAutoconfigured());
774 $this->assertFalse($container->getDefinition('override_defaults_settings_to_false')->isAutoconfigured());
777 public function testBindings()
779 $container = new ContainerBuilder();
780 $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
781 $loader->load('services_bindings.xml');
782 $container->compile();
784 $definition = $container->getDefinition('bar');
785 $this->assertEquals(array(
786 'NonExistent' => null,
787 BarInterface::class => new Reference(Bar::class),
788 '$foo' => array(null),
790 '$factory' => 'factory',
791 ), array_map(function ($v) { return $v->getValues()[0]; }, $definition->getBindings()));
792 $this->assertEquals(array(
795 new Reference(Bar::class),
797 ), $definition->getArguments());
799 $definition = $container->getDefinition(Bar::class);
800 $this->assertEquals(array(
803 ), $definition->getArguments());
804 $this->assertEquals(array(
805 'NonExistent' => null,
807 '$factory' => 'factory',
808 ), array_map(function ($v) { return $v->getValues()[0]; }, $definition->getBindings()));