YamlFileLoaderTest.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  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\DependencyInjection\Loader\PhpFileLoader;
  19. use Symfony\Component\Config\Loader\LoaderResolver;
  20. use Symfony\Component\Config\FileLocator;
  21. use Symfony\Component\Config\Resource\FileResource;
  22. use Symfony\Component\Config\Resource\GlobResource;
  23. use Symfony\Component\DependencyInjection\Tests\Fixtures\CaseSensitiveClass;
  24. use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype;
  25. use Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy;
  26. use Symfony\Component\ExpressionLanguage\Expression;
  27. class YamlFileLoaderTest extends TestCase
  28. {
  29. protected static $fixturesPath;
  30. public static function setUpBeforeClass()
  31. {
  32. self::$fixturesPath = realpath(__DIR__.'/../Fixtures/');
  33. require_once self::$fixturesPath.'/includes/foo.php';
  34. require_once self::$fixturesPath.'/includes/ProjectExtension.php';
  35. }
  36. /**
  37. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  38. * @expectedExceptionMessageRegExp /The file ".+" does not exist./
  39. */
  40. public function testLoadUnExistFile()
  41. {
  42. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/ini'));
  43. $r = new \ReflectionObject($loader);
  44. $m = $r->getMethod('loadFile');
  45. $m->setAccessible(true);
  46. $m->invoke($loader, 'foo.yml');
  47. }
  48. /**
  49. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  50. * @expectedExceptionMessageRegExp /The file ".+" does not contain valid YAML./
  51. */
  52. public function testLoadInvalidYamlFile()
  53. {
  54. $path = self::$fixturesPath.'/ini';
  55. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator($path));
  56. $r = new \ReflectionObject($loader);
  57. $m = $r->getMethod('loadFile');
  58. $m->setAccessible(true);
  59. $m->invoke($loader, $path.'/parameters.ini');
  60. }
  61. /**
  62. * @dataProvider provideInvalidFiles
  63. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  64. */
  65. public function testLoadInvalidFile($file)
  66. {
  67. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  68. $loader->load($file.'.yml');
  69. }
  70. public function provideInvalidFiles()
  71. {
  72. return array(
  73. array('bad_parameters'),
  74. array('bad_imports'),
  75. array('bad_import'),
  76. array('bad_services'),
  77. array('bad_service'),
  78. array('bad_calls'),
  79. array('bad_format'),
  80. array('nonvalid1'),
  81. array('nonvalid2'),
  82. );
  83. }
  84. public function testLoadParameters()
  85. {
  86. $container = new ContainerBuilder();
  87. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  88. $loader->load('services2.yml');
  89. $this->assertEquals(array('foo' => 'bar', 'mixedcase' => array('MixedCaseKey' => 'value'), 'values' => array(true, false, 0, 1000.3, PHP_INT_MAX), 'bar' => 'foo', 'escape' => '@escapeme', 'foo_bar' => new Reference('foo_bar')), $container->getParameterBag()->all(), '->load() converts YAML keys to lowercase');
  90. }
  91. public function testLoadImports()
  92. {
  93. $container = new ContainerBuilder();
  94. $resolver = new LoaderResolver(array(
  95. new IniFileLoader($container, new FileLocator(self::$fixturesPath.'/ini')),
  96. new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')),
  97. new PhpFileLoader($container, new FileLocator(self::$fixturesPath.'/php')),
  98. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')),
  99. ));
  100. $loader->setResolver($resolver);
  101. $loader->load('services4.yml');
  102. $actual = $container->getParameterBag()->all();
  103. $expected = array(
  104. 'foo' => 'bar',
  105. 'values' => array(true, false, PHP_INT_MAX),
  106. 'bar' => '%foo%',
  107. 'escape' => '@escapeme',
  108. 'foo_bar' => new Reference('foo_bar'),
  109. 'mixedcase' => array('MixedCaseKey' => 'value'),
  110. 'imported_from_ini' => true,
  111. 'imported_from_xml' => true,
  112. 'with_wrong_ext' => 'from yaml',
  113. );
  114. $this->assertEquals(array_keys($expected), array_keys($actual), '->load() imports and merges imported files');
  115. $this->assertTrue($actual['imported_from_ini']);
  116. // Bad import throws no exception due to ignore_errors value.
  117. $loader->load('services4_bad_import.yml');
  118. }
  119. public function testLoadServices()
  120. {
  121. $container = new ContainerBuilder();
  122. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  123. $loader->load('services6.yml');
  124. $services = $container->getDefinitions();
  125. $this->assertArrayHasKey('foo', $services, '->load() parses service elements');
  126. $this->assertFalse($services['not_shared']->isShared(), '->load() parses the shared flag');
  127. $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Definition', $services['foo'], '->load() converts service element to Definition instances');
  128. $this->assertEquals('FooClass', $services['foo']->getClass(), '->load() parses the class attribute');
  129. $this->assertEquals('%path%/foo.php', $services['file']->getFile(), '->load() parses the file tag');
  130. $this->assertEquals(array('foo', new Reference('foo'), array(true, false)), $services['arguments']->getArguments(), '->load() parses the argument tags');
  131. $this->assertEquals('sc_configure', $services['configurator1']->getConfigurator(), '->load() parses the configurator tag');
  132. $this->assertEquals(array(new Reference('baz'), 'configure'), $services['configurator2']->getConfigurator(), '->load() parses the configurator tag');
  133. $this->assertEquals(array('BazClass', 'configureStatic'), $services['configurator3']->getConfigurator(), '->load() parses the configurator tag');
  134. $this->assertEquals(array(array('setBar', 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');
  135. $this->assertEquals(array(array('setBar', array('foo', new Reference('foo'), array(true, false)))), $services['method_call2']->getMethodCalls(), '->load() parses the method_call tag');
  136. $this->assertEquals('factory', $services['new_factory1']->getFactory(), '->load() parses the factory tag');
  137. $this->assertEquals(array(new Reference('baz'), 'getClass'), $services['new_factory2']->getFactory(), '->load() parses the factory tag');
  138. $this->assertEquals(array('BazClass', 'getInstance'), $services['new_factory3']->getFactory(), '->load() parses the factory tag');
  139. $this->assertSame(array(null, 'getInstance'), $services['new_factory4']->getFactory(), '->load() accepts factory tag without class');
  140. $this->assertEquals(array('foo', new Reference('baz')), $services['Acme\WithShortCutArgs']->getArguments(), '->load() parses short service definition');
  141. $aliases = $container->getAliases();
  142. $this->assertArrayHasKey('alias_for_foo', $aliases, '->load() parses aliases');
  143. $this->assertEquals('foo', (string) $aliases['alias_for_foo'], '->load() parses aliases');
  144. $this->assertTrue($aliases['alias_for_foo']->isPublic());
  145. $this->assertArrayHasKey('another_alias_for_foo', $aliases);
  146. $this->assertEquals('foo', (string) $aliases['another_alias_for_foo']);
  147. $this->assertFalse($aliases['another_alias_for_foo']->isPublic());
  148. $this->assertTrue(isset($aliases['another_third_alias_for_foo']));
  149. $this->assertEquals('foo', (string) $aliases['another_third_alias_for_foo']);
  150. $this->assertTrue($aliases['another_third_alias_for_foo']->isPublic());
  151. $this->assertEquals(array('decorated', null, 0), $services['decorator_service']->getDecoratedService());
  152. $this->assertEquals(array('decorated', 'decorated.pif-pouf', 0), $services['decorator_service_with_name']->getDecoratedService());
  153. $this->assertEquals(array('decorated', 'decorated.pif-pouf', 5), $services['decorator_service_with_name_and_priority']->getDecoratedService());
  154. }
  155. public function testLoadFactoryShortSyntax()
  156. {
  157. $container = new ContainerBuilder();
  158. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  159. $loader->load('services14.yml');
  160. $services = $container->getDefinitions();
  161. $this->assertEquals(array(new Reference('baz'), 'getClass'), $services['factory']->getFactory(), '->load() parses the factory tag with service:method');
  162. $this->assertEquals(array('FooBacFactory', 'createFooBar'), $services['factory_with_static_call']->getFactory(), '->load() parses the factory tag with Class::method');
  163. }
  164. public function testLoadConfiguratorShortSyntax()
  165. {
  166. $container = new ContainerBuilder();
  167. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  168. $loader->load('services_configurator_short_syntax.yml');
  169. $services = $container->getDefinitions();
  170. $this->assertEquals(array(new Reference('foo_bar_configurator'), 'configure'), $services['foo_bar']->getConfigurator(), '->load() parses the configurator tag with service:method');
  171. $this->assertEquals(array('FooBarConfigurator', 'configureFooBar'), $services['foo_bar_with_static_call']->getConfigurator(), '->load() parses the configurator tag with Class::method');
  172. }
  173. public function testExtensions()
  174. {
  175. $container = new ContainerBuilder();
  176. $container->registerExtension(new \ProjectExtension());
  177. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  178. $loader->load('services10.yml');
  179. $container->compile();
  180. $services = $container->getDefinitions();
  181. $parameters = $container->getParameterBag()->all();
  182. $this->assertArrayHasKey('project.service.bar', $services, '->load() parses extension elements');
  183. $this->assertArrayHasKey('project.parameter.bar', $parameters, '->load() parses extension elements');
  184. $this->assertEquals('BAR', $services['project.service.foo']->getClass(), '->load() parses extension elements');
  185. $this->assertEquals('BAR', $parameters['project.parameter.foo'], '->load() parses extension elements');
  186. try {
  187. $loader->load('services11.yml');
  188. $this->fail('->load() throws an InvalidArgumentException if the tag is not valid');
  189. } catch (\Exception $e) {
  190. $this->assertInstanceOf('\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the tag is not valid');
  191. $this->assertStringStartsWith('There is no extension able to load the configuration for "foobarfoobar" (in', $e->getMessage(), '->load() throws an InvalidArgumentException if the tag is not valid');
  192. }
  193. }
  194. public function testExtensionWithNullConfig()
  195. {
  196. $container = new ContainerBuilder();
  197. $container->registerExtension(new \ProjectExtension());
  198. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  199. $loader->load('null_config.yml');
  200. $container->compile();
  201. $this->assertSame(array(null), $container->getParameter('project.configs'));
  202. }
  203. public function testSupports()
  204. {
  205. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator());
  206. $this->assertTrue($loader->supports('foo.yml'), '->supports() returns true if the resource is loadable');
  207. $this->assertTrue($loader->supports('foo.yaml'), '->supports() returns true if the resource is loadable');
  208. $this->assertFalse($loader->supports('foo.foo'), '->supports() returns false if the resource is not loadable');
  209. $this->assertTrue($loader->supports('with_wrong_ext.xml', 'yml'), '->supports() returns true if the resource with forced type is loadable');
  210. $this->assertTrue($loader->supports('with_wrong_ext.xml', 'yaml'), '->supports() returns true if the resource with forced type is loadable');
  211. }
  212. public function testNonArrayTagsThrowsException()
  213. {
  214. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  215. try {
  216. $loader->load('badtag1.yml');
  217. $this->fail('->load() should throw an exception when the tags key of a service is not an array');
  218. } catch (\Exception $e) {
  219. $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the tags key is not an array');
  220. $this->assertStringStartsWith('Parameter "tags" must be an array for service', $e->getMessage(), '->load() throws an InvalidArgumentException if the tags key is not an array');
  221. }
  222. }
  223. public function testTagWithoutNameThrowsException()
  224. {
  225. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  226. try {
  227. $loader->load('badtag2.yml');
  228. $this->fail('->load() should throw an exception when a tag is missing the name key');
  229. } catch (\Exception $e) {
  230. $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if a tag is missing the name key');
  231. $this->assertStringStartsWith('A "tags" entry is missing a "name" key for service ', $e->getMessage(), '->load() throws an InvalidArgumentException if a tag is missing the name key');
  232. }
  233. }
  234. public function testNameOnlyTagsAreAllowedAsString()
  235. {
  236. $container = new ContainerBuilder();
  237. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  238. $loader->load('tag_name_only.yml');
  239. $this->assertCount(1, $container->getDefinition('foo_service')->getTag('foo'));
  240. }
  241. public function testTagWithAttributeArrayThrowsException()
  242. {
  243. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  244. try {
  245. $loader->load('badtag3.yml');
  246. $this->fail('->load() should throw an exception when a tag-attribute is not a scalar');
  247. } catch (\Exception $e) {
  248. $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if a tag-attribute is not a scalar');
  249. $this->assertStringStartsWith('A "tags" attribute must be of a scalar-type for service "foo_service", tag "foo", attribute "bar"', $e->getMessage(), '->load() throws an InvalidArgumentException if a tag-attribute is not a scalar');
  250. }
  251. }
  252. public function testLoadYamlOnlyWithKeys()
  253. {
  254. $container = new ContainerBuilder();
  255. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  256. $loader->load('services21.yml');
  257. $definition = $container->getDefinition('manager');
  258. $this->assertEquals(array(array('setLogger', array(new Reference('logger'))), array('setClass', array('User'))), $definition->getMethodCalls());
  259. $this->assertEquals(array(true), $definition->getArguments());
  260. $this->assertEquals(array('manager' => array(array('alias' => 'user'))), $definition->getTags());
  261. }
  262. /**
  263. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  264. * @expectedExceptionMessageRegExp /The tag name for service ".+" in .+ must be a non-empty string/
  265. */
  266. public function testTagWithEmptyNameThrowsException()
  267. {
  268. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  269. $loader->load('tag_name_empty_string.yml');
  270. }
  271. /**
  272. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  273. * @expectedExceptionMessageREgExp /The tag name for service "\.+" must be a non-empty string/
  274. */
  275. public function testTagWithNonStringNameThrowsException()
  276. {
  277. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  278. $loader->load('tag_name_no_string.yml');
  279. }
  280. /**
  281. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  282. */
  283. public function testTypesNotArray()
  284. {
  285. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  286. $loader->load('bad_types1.yml');
  287. }
  288. /**
  289. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  290. */
  291. public function testTypeNotString()
  292. {
  293. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  294. $loader->load('bad_types2.yml');
  295. }
  296. /**
  297. * @group legacy
  298. */
  299. public function testTypes()
  300. {
  301. $container = new ContainerBuilder();
  302. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  303. $loader->load('services22.yml');
  304. $this->assertEquals(array('Foo', 'Bar'), $container->getDefinition('foo_service')->getAutowiringTypes());
  305. $this->assertEquals(array('Foo'), $container->getDefinition('baz_service')->getAutowiringTypes());
  306. }
  307. public function testParsesIteratorArgument()
  308. {
  309. $container = new ContainerBuilder();
  310. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  311. $loader->load('services9.yml');
  312. $lazyDefinition = $container->getDefinition('lazy_context');
  313. $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');
  314. }
  315. public function testAutowire()
  316. {
  317. $container = new ContainerBuilder();
  318. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  319. $loader->load('services23.yml');
  320. $this->assertTrue($container->getDefinition('bar_service')->isAutowired());
  321. }
  322. public function testClassFromId()
  323. {
  324. $container = new ContainerBuilder();
  325. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  326. $loader->load('class_from_id.yml');
  327. $container->compile();
  328. $this->assertEquals(CaseSensitiveClass::class, $container->getDefinition(CaseSensitiveClass::class)->getClass());
  329. }
  330. public function testPrototype()
  331. {
  332. $container = new ContainerBuilder();
  333. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  334. $loader->load('services_prototype.yml');
  335. $ids = array_keys($container->getDefinitions());
  336. sort($ids);
  337. $this->assertSame(array(Prototype\Foo::class, Prototype\Sub\Bar::class, 'service_container'), $ids);
  338. $resources = $container->getResources();
  339. $fixturesDir = dirname(__DIR__).DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR;
  340. $this->assertTrue(false !== array_search(new FileResource($fixturesDir.'yaml'.DIRECTORY_SEPARATOR.'services_prototype.yml'), $resources));
  341. $this->assertTrue(false !== array_search(new GlobResource($fixturesDir.'Prototype', '', true), $resources));
  342. $resources = array_map('strval', $resources);
  343. $this->assertContains('reflection.Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Foo', $resources);
  344. $this->assertContains('reflection.Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Sub\Bar', $resources);
  345. }
  346. public function testDefaults()
  347. {
  348. $container = new ContainerBuilder();
  349. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  350. $loader->load('services28.yml');
  351. $this->assertFalse($container->getDefinition('with_defaults')->isPublic());
  352. $this->assertSame(array('foo' => array(array())), $container->getDefinition('with_defaults')->getTags());
  353. $this->assertTrue($container->getDefinition('with_defaults')->isAutowired());
  354. $this->assertArrayNotHasKey('public', $container->getDefinition('with_defaults')->getChanges());
  355. $this->assertArrayNotHasKey('autowire', $container->getDefinition('with_defaults')->getChanges());
  356. $this->assertFalse($container->getAlias('with_defaults_aliased')->isPublic());
  357. $this->assertFalse($container->getAlias('with_defaults_aliased_short')->isPublic());
  358. $this->assertFalse($container->getDefinition('Acme\WithShortCutArgs')->isPublic());
  359. $this->assertSame(array('foo' => array(array())), $container->getDefinition('Acme\WithShortCutArgs')->getTags());
  360. $this->assertTrue($container->getDefinition('Acme\WithShortCutArgs')->isAutowired());
  361. $container->compile();
  362. $this->assertTrue($container->getDefinition('with_null')->isPublic());
  363. $this->assertTrue($container->getDefinition('no_defaults')->isPublic());
  364. // foo tag is inherited from defaults
  365. $this->assertSame(array('foo' => array(array())), $container->getDefinition('with_null')->getTags());
  366. $this->assertSame(array('foo' => array(array())), $container->getDefinition('no_defaults')->getTags());
  367. $this->assertTrue($container->getDefinition('with_null')->isAutowired());
  368. $this->assertFalse($container->getDefinition('no_defaults')->isAutowired());
  369. $this->assertTrue($container->getDefinition('child_def')->isPublic());
  370. $this->assertSame(array('foo' => array(array())), $container->getDefinition('child_def')->getTags());
  371. $this->assertFalse($container->getDefinition('child_def')->isAutowired());
  372. }
  373. public function testNamedArguments()
  374. {
  375. $container = new ContainerBuilder();
  376. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  377. $loader->load('services_named_args.yml');
  378. $this->assertEquals(array(null, '$apiKey' => 'ABCD'), $container->getDefinition(NamedArgumentsDummy::class)->getArguments());
  379. $this->assertEquals(array(null, '$apiKey' => 'ABCD'), $container->getDefinition('another_one')->getArguments());
  380. $container->compile();
  381. $this->assertEquals(array(null, 'ABCD'), $container->getDefinition(NamedArgumentsDummy::class)->getArguments());
  382. $this->assertEquals(array(null, 'ABCD'), $container->getDefinition('another_one')->getArguments());
  383. $this->assertEquals(array(array('setApiKey', array('123'))), $container->getDefinition('another_one')->getMethodCalls());
  384. }
  385. public function testInstanceof()
  386. {
  387. $container = new ContainerBuilder();
  388. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  389. $loader->load('services_instanceof.yml');
  390. $container->compile();
  391. $definition = $container->getDefinition(Foo::class);
  392. $this->assertTrue($definition->isAutowired());
  393. $this->assertTrue($definition->isLazy());
  394. $this->assertSame(array('foo' => array(array()), 'bar' => array(array())), $definition->getTags());
  395. }
  396. /**
  397. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  398. * @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.
  399. */
  400. public function testInstanceOfAndChildDefinitionNotAllowed()
  401. {
  402. $container = new ContainerBuilder();
  403. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  404. $loader->load('services_instanceof_with_parent.yml');
  405. $container->compile();
  406. }
  407. /**
  408. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  409. * @expectedExceptionMessage The service "child_service" cannot have a "parent" and also have "autoconfigure". Try setting "autoconfigure: false" for the service.
  410. */
  411. public function testAutoConfigureAndChildDefinitionNotAllowed()
  412. {
  413. $container = new ContainerBuilder();
  414. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  415. $loader->load('services_autoconfigure_with_parent.yml');
  416. $container->compile();
  417. }
  418. /**
  419. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  420. * @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.
  421. */
  422. public function testDefaultsAndChildDefinitionNotAllowed()
  423. {
  424. $container = new ContainerBuilder();
  425. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  426. $loader->load('services_defaults_with_parent.yml');
  427. $container->compile();
  428. }
  429. /**
  430. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  431. * @expectedExceptionMessage The value of the "decorates" option for the "bar" service must be the id of the service without the "@" prefix (replace "@foo" with "foo").
  432. */
  433. public function testDecoratedServicesWithWrongSyntaxThrowsException()
  434. {
  435. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  436. $loader->load('bad_decorates.yml');
  437. }
  438. /**
  439. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  440. * @expectedExceptionMessageRegExp /Parameter "tags" must be an array for service "Foo\\Bar" in .+services31_invalid_tags\.yml\. Check your YAML syntax./
  441. */
  442. public function testInvalidTagsWithDefaults()
  443. {
  444. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  445. $loader->load('services31_invalid_tags.yml');
  446. }
  447. /**
  448. * @group legacy
  449. * @expectedDeprecation Service names that start with an underscore are deprecated since Symfony 3.3 and will be reserved in 4.0. Rename the "_foo" service or define it in XML instead.
  450. */
  451. public function testUnderscoreServiceId()
  452. {
  453. $container = new ContainerBuilder();
  454. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  455. $loader->load('services_underscore.yml');
  456. }
  457. public function testAnonymousServices()
  458. {
  459. $container = new ContainerBuilder();
  460. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  461. $loader->load('anonymous_services.yml');
  462. $definition = $container->getDefinition('Foo');
  463. $this->assertTrue($definition->isAutowired());
  464. // Anonymous service in an argument
  465. $args = $definition->getArguments();
  466. $this->assertCount(1, $args);
  467. $this->assertInstanceOf(Reference::class, $args[0]);
  468. $this->assertTrue($container->has((string) $args[0]));
  469. $this->assertRegExp('/^\d+_[A-Za-z0-9]{64}$/', (string) $args[0]);
  470. $anonymous = $container->getDefinition((string) $args[0]);
  471. $this->assertEquals('Bar', $anonymous->getClass());
  472. $this->assertFalse($anonymous->isPublic());
  473. $this->assertTrue($anonymous->isAutowired());
  474. // Anonymous service in a callable
  475. $factory = $definition->getFactory();
  476. $this->assertInternalType('array', $factory);
  477. $this->assertInstanceOf(Reference::class, $factory[0]);
  478. $this->assertTrue($container->has((string) $factory[0]));
  479. $this->assertRegExp('/^\d+_[A-Za-z0-9]{64}$/', (string) $factory[0]);
  480. $this->assertEquals('constructFoo', $factory[1]);
  481. $anonymous = $container->getDefinition((string) $factory[0]);
  482. $this->assertEquals('Quz', $anonymous->getClass());
  483. $this->assertFalse($anonymous->isPublic());
  484. $this->assertFalse($anonymous->isAutowired());
  485. }
  486. public function testAnonymousServicesInDifferentFilesWithSameNameDoNotConflict()
  487. {
  488. $container = new ContainerBuilder();
  489. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml/foo'));
  490. $loader->load('services.yml');
  491. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml/bar'));
  492. $loader->load('services.yml');
  493. $this->assertCount(5, $container->getDefinitions());
  494. }
  495. public function testAnonymousServicesInInstanceof()
  496. {
  497. $container = new ContainerBuilder();
  498. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  499. $loader->load('anonymous_services_in_instanceof.yml');
  500. $definition = $container->getDefinition('Dummy');
  501. $instanceof = $definition->getInstanceofConditionals();
  502. $this->assertCount(3, $instanceof);
  503. $this->assertArrayHasKey('DummyInterface', $instanceof);
  504. $args = $instanceof['DummyInterface']->getProperties();
  505. $this->assertCount(1, $args);
  506. $this->assertInstanceOf(Reference::class, $args['foo']);
  507. $this->assertTrue($container->has((string) $args['foo']));
  508. $anonymous = $container->getDefinition((string) $args['foo']);
  509. $this->assertEquals('Anonymous', $anonymous->getClass());
  510. $this->assertFalse($anonymous->isPublic());
  511. $this->assertEmpty($anonymous->getInstanceofConditionals());
  512. $this->assertFalse($container->has('Bar'));
  513. }
  514. /**
  515. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  516. * @expectedExceptionMessageRegExp /Creating an alias using the tag "!service" is not allowed in ".+anonymous_services_alias\.yml"\./
  517. */
  518. public function testAnonymousServicesWithAliases()
  519. {
  520. $container = new ContainerBuilder();
  521. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  522. $loader->load('anonymous_services_alias.yml');
  523. }
  524. /**
  525. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  526. * @expectedExceptionMessageRegExp /Using an anonymous service in a parameter is not allowed in ".+anonymous_services_in_parameters\.yml"\./
  527. */
  528. public function testAnonymousServicesInParameters()
  529. {
  530. $container = new ContainerBuilder();
  531. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  532. $loader->load('anonymous_services_in_parameters.yml');
  533. }
  534. public function testAutoConfigureInstanceof()
  535. {
  536. $container = new ContainerBuilder();
  537. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  538. $loader->load('services_autoconfigure.yml');
  539. $this->assertTrue($container->getDefinition('use_defaults_settings')->isAutoconfigured());
  540. $this->assertFalse($container->getDefinition('override_defaults_settings_to_false')->isAutoconfigured());
  541. }
  542. /**
  543. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  544. * @expectedExceptionMessageRegExp /Service "_defaults" key must be an array, "NULL" given in ".+bad_empty_defaults\.yml"\./
  545. */
  546. public function testEmptyDefaultsThrowsClearException()
  547. {
  548. $container = new ContainerBuilder();
  549. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  550. $loader->load('bad_empty_defaults.yml');
  551. }
  552. /**
  553. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  554. * @expectedExceptionMessageRegExp /Service "_instanceof" key must be an array, "NULL" given in ".+bad_empty_instanceof\.yml"\./
  555. */
  556. public function testEmptyInstanceofThrowsClearException()
  557. {
  558. $container = new ContainerBuilder();
  559. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  560. $loader->load('bad_empty_instanceof.yml');
  561. }
  562. }
  563. interface FooInterface
  564. {
  565. }
  566. class Foo implements FooInterface
  567. {
  568. }