YamlFileLoaderTest.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\DependencyInjection\Tests\Loader;
  11. use PHPUnit\Framework\TestCase;
  12. use Symfony\Component\Config\FileLocator;
  13. use Symfony\Component\Config\Loader\LoaderResolver;
  14. use Symfony\Component\DependencyInjection\ContainerBuilder;
  15. use Symfony\Component\DependencyInjection\Loader\IniFileLoader;
  16. use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
  17. use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
  18. use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
  19. use Symfony\Component\DependencyInjection\Reference;
  20. use Symfony\Component\ExpressionLanguage\Expression;
  21. class YamlFileLoaderTest extends TestCase
  22. {
  23. protected static $fixturesPath;
  24. public static function setUpBeforeClass()
  25. {
  26. self::$fixturesPath = realpath(__DIR__.'/../Fixtures/');
  27. require_once self::$fixturesPath.'/includes/foo.php';
  28. require_once self::$fixturesPath.'/includes/ProjectExtension.php';
  29. }
  30. /**
  31. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  32. * @expectedExceptionMessageRegExp /The file ".+" does not exist./
  33. */
  34. public function testLoadUnExistFile()
  35. {
  36. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/ini'));
  37. $r = new \ReflectionObject($loader);
  38. $m = $r->getMethod('loadFile');
  39. $m->setAccessible(true);
  40. $m->invoke($loader, 'foo.yml');
  41. }
  42. /**
  43. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  44. * @expectedExceptionMessageRegExp /The file ".+" does not contain valid YAML./
  45. */
  46. public function testLoadInvalidYamlFile()
  47. {
  48. $path = self::$fixturesPath.'/ini';
  49. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator($path));
  50. $r = new \ReflectionObject($loader);
  51. $m = $r->getMethod('loadFile');
  52. $m->setAccessible(true);
  53. $m->invoke($loader, $path.'/parameters.ini');
  54. }
  55. /**
  56. * @dataProvider provideInvalidFiles
  57. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  58. */
  59. public function testLoadInvalidFile($file)
  60. {
  61. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  62. $loader->load($file.'.yml');
  63. }
  64. public function provideInvalidFiles()
  65. {
  66. return array(
  67. array('bad_parameters'),
  68. array('bad_imports'),
  69. array('bad_import'),
  70. array('bad_services'),
  71. array('bad_service'),
  72. array('bad_calls'),
  73. array('bad_format'),
  74. array('nonvalid1'),
  75. array('nonvalid2'),
  76. );
  77. }
  78. public function testLoadParameters()
  79. {
  80. $container = new ContainerBuilder();
  81. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  82. $loader->load('services2.yml');
  83. $this->assertEquals(array('foo' => 'bar', 'mixedcase' => array('MixedCaseKey' => 'value'), 'values' => array(true, false, 0, 1000.3), 'bar' => 'foo', 'escape' => '@escapeme', 'foo_bar' => new Reference('foo_bar')), $container->getParameterBag()->all(), '->load() converts YAML keys to lowercase');
  84. }
  85. public function testLoadImports()
  86. {
  87. $container = new ContainerBuilder();
  88. $resolver = new LoaderResolver(array(
  89. new IniFileLoader($container, new FileLocator(self::$fixturesPath.'/ini')),
  90. new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')),
  91. new PhpFileLoader($container, new FileLocator(self::$fixturesPath.'/php')),
  92. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')),
  93. ));
  94. $loader->setResolver($resolver);
  95. $loader->load('services4.yml');
  96. $actual = $container->getParameterBag()->all();
  97. $expected = array('foo' => 'bar', 'values' => array(true, false), 'bar' => '%foo%', 'escape' => '@escapeme', 'foo_bar' => new Reference('foo_bar'), 'mixedcase' => array('MixedCaseKey' => 'value'), 'imported_from_ini' => true, 'imported_from_xml' => true);
  98. $this->assertEquals(array_keys($expected), array_keys($actual), '->load() imports and merges imported files');
  99. // Bad import throws no exception due to ignore_errors value.
  100. $loader->load('services4_bad_import.yml');
  101. }
  102. /**
  103. * @group legacy
  104. */
  105. public function testLegacyLoadServices()
  106. {
  107. $container = new ContainerBuilder();
  108. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  109. $loader->load('legacy-services6.yml');
  110. $services = $container->getDefinitions();
  111. $this->assertEquals('FooClass', $services['constructor']->getClass());
  112. $this->assertEquals('getInstance', $services['constructor']->getFactoryMethod());
  113. $this->assertEquals('BazClass', $services['factory_service']->getClass());
  114. $this->assertEquals('baz_factory', $services['factory_service']->getFactoryService());
  115. $this->assertEquals('getInstance', $services['factory_service']->getFactoryMethod());
  116. $this->assertEquals('container', $services['scope.container']->getScope());
  117. $this->assertEquals('custom', $services['scope.custom']->getScope());
  118. $this->assertEquals('prototype', $services['scope.prototype']->getScope());
  119. $this->assertTrue($services['request']->isSynthetic(), '->load() parses the synthetic flag');
  120. $this->assertTrue($services['request']->isSynchronized(), '->load() parses the synchronized flag');
  121. $this->assertTrue($services['request']->isLazy(), '->load() parses the lazy flag');
  122. $this->assertNull($services['request']->getDecoratedService());
  123. }
  124. public function testLoadServices()
  125. {
  126. $container = new ContainerBuilder();
  127. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  128. $loader->load('services6.yml');
  129. $services = $container->getDefinitions();
  130. $this->assertArrayHasKey('foo', $services, '->load() parses service elements');
  131. $this->assertFalse($services['not_shared']->isShared(), '->load() parses the shared flag');
  132. $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Definition', $services['foo'], '->load() converts service element to Definition instances');
  133. $this->assertEquals('FooClass', $services['foo']->getClass(), '->load() parses the class attribute');
  134. $this->assertEquals('%path%/foo.php', $services['file']->getFile(), '->load() parses the file tag');
  135. $this->assertEquals(array('foo', new Reference('foo'), array(true, false)), $services['arguments']->getArguments(), '->load() parses the argument tags');
  136. $this->assertEquals('sc_configure', $services['configurator1']->getConfigurator(), '->load() parses the configurator tag');
  137. $this->assertEquals(array(new Reference('baz'), 'configure'), $services['configurator2']->getConfigurator(), '->load() parses the configurator tag');
  138. $this->assertEquals(array('BazClass', 'configureStatic'), $services['configurator3']->getConfigurator(), '->load() parses the configurator tag');
  139. $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');
  140. $this->assertEquals(array(array('setBar', array('foo', new Reference('foo'), array(true, false)))), $services['method_call2']->getMethodCalls(), '->load() parses the method_call tag');
  141. $this->assertEquals('factory', $services['new_factory1']->getFactory(), '->load() parses the factory tag');
  142. $this->assertEquals(array(new Reference('baz'), 'getClass'), $services['new_factory2']->getFactory(), '->load() parses the factory tag');
  143. $this->assertEquals(array('BazClass', 'getInstance'), $services['new_factory3']->getFactory(), '->load() parses the factory tag');
  144. $aliases = $container->getAliases();
  145. $this->assertArrayHasKey('alias_for_foo', $aliases, '->load() parses aliases');
  146. $this->assertEquals('foo', (string) $aliases['alias_for_foo'], '->load() parses aliases');
  147. $this->assertTrue($aliases['alias_for_foo']->isPublic());
  148. $this->assertArrayHasKey('another_alias_for_foo', $aliases);
  149. $this->assertEquals('foo', (string) $aliases['another_alias_for_foo']);
  150. $this->assertFalse($aliases['another_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 testExtensions()
  165. {
  166. $container = new ContainerBuilder();
  167. $container->registerExtension(new \ProjectExtension());
  168. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  169. $loader->load('services10.yml');
  170. $container->compile();
  171. $services = $container->getDefinitions();
  172. $parameters = $container->getParameterBag()->all();
  173. $this->assertArrayHasKey('project.service.bar', $services, '->load() parses extension elements');
  174. $this->assertArrayHasKey('project.parameter.bar', $parameters, '->load() parses extension elements');
  175. $this->assertEquals('BAR', $services['project.service.foo']->getClass(), '->load() parses extension elements');
  176. $this->assertEquals('BAR', $parameters['project.parameter.foo'], '->load() parses extension elements');
  177. try {
  178. $loader->load('services11.yml');
  179. $this->fail('->load() throws an InvalidArgumentException if the tag is not valid');
  180. } catch (\Exception $e) {
  181. $this->assertInstanceOf('\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the tag is not valid');
  182. $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');
  183. }
  184. }
  185. public function testExtensionWithNullConfig()
  186. {
  187. $container = new ContainerBuilder();
  188. $container->registerExtension(new \ProjectExtension());
  189. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  190. $loader->load('null_config.yml');
  191. $container->compile();
  192. $this->assertSame(array(null), $container->getParameter('project.configs'));
  193. }
  194. public function testSupports()
  195. {
  196. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator());
  197. $this->assertTrue($loader->supports('foo.yml'), '->supports() returns true if the resource is loadable');
  198. $this->assertTrue($loader->supports('foo.yaml'), '->supports() returns true if the resource is loadable');
  199. $this->assertFalse($loader->supports('foo.foo'), '->supports() returns true if the resource is loadable');
  200. }
  201. public function testNonArrayTagsThrowsException()
  202. {
  203. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  204. try {
  205. $loader->load('badtag1.yml');
  206. $this->fail('->load() should throw an exception when the tags key of a service is not an array');
  207. } catch (\Exception $e) {
  208. $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the tags key is not an array');
  209. $this->assertStringStartsWith('Parameter "tags" must be an array for service', $e->getMessage(), '->load() throws an InvalidArgumentException if the tags key is not an array');
  210. }
  211. }
  212. /**
  213. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  214. * @expectedExceptionMessage A "tags" entry must be an array for service
  215. */
  216. public function testNonArrayTagThrowsException()
  217. {
  218. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  219. $loader->load('badtag4.yml');
  220. }
  221. public function testTagWithoutNameThrowsException()
  222. {
  223. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  224. try {
  225. $loader->load('badtag2.yml');
  226. $this->fail('->load() should throw an exception when a tag is missing the name key');
  227. } catch (\Exception $e) {
  228. $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if a tag is missing the name key');
  229. $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');
  230. }
  231. }
  232. public function testTagWithAttributeArrayThrowsException()
  233. {
  234. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  235. try {
  236. $loader->load('badtag3.yml');
  237. $this->fail('->load() should throw an exception when a tag-attribute is not a scalar');
  238. } catch (\Exception $e) {
  239. $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if a tag-attribute is not a scalar');
  240. $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');
  241. }
  242. }
  243. public function testLoadYamlOnlyWithKeys()
  244. {
  245. $container = new ContainerBuilder();
  246. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  247. $loader->load('services21.yml');
  248. $definition = $container->getDefinition('manager');
  249. $this->assertEquals(array(array('setLogger', array(new Reference('logger'))), array('setClass', array('User'))), $definition->getMethodCalls());
  250. $this->assertEquals(array(true), $definition->getArguments());
  251. $this->assertEquals(array('manager' => array(array('alias' => 'user'))), $definition->getTags());
  252. }
  253. /**
  254. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  255. * @expectedExceptionMessageRegExp /The tag name for service ".+" in .+ must be a non-empty string/
  256. */
  257. public function testTagWithEmptyNameThrowsException()
  258. {
  259. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  260. $loader->load('tag_name_empty_string.yml');
  261. }
  262. /**
  263. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  264. * @expectedExceptionMessageREgExp /The tag name for service "\.+" must be a non-empty string/
  265. */
  266. public function testTagWithNonStringNameThrowsException()
  267. {
  268. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  269. $loader->load('tag_name_no_string.yml');
  270. }
  271. /**
  272. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  273. */
  274. public function testTypesNotArray()
  275. {
  276. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  277. $loader->load('bad_types1.yml');
  278. }
  279. /**
  280. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  281. */
  282. public function testTypeNotString()
  283. {
  284. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  285. $loader->load('bad_types2.yml');
  286. }
  287. public function testTypes()
  288. {
  289. $container = new ContainerBuilder();
  290. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  291. $loader->load('services22.yml');
  292. $this->assertEquals(array('Foo', 'Bar'), $container->getDefinition('foo_service')->getAutowiringTypes());
  293. $this->assertEquals(array('Foo'), $container->getDefinition('baz_service')->getAutowiringTypes());
  294. }
  295. public function testAutowire()
  296. {
  297. $container = new ContainerBuilder();
  298. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  299. $loader->load('services23.yml');
  300. $this->assertTrue($container->getDefinition('bar_service')->isAutowired());
  301. }
  302. /**
  303. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  304. * @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").
  305. */
  306. public function testDecoratedServicesWithWrongSyntaxThrowsException()
  307. {
  308. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  309. $loader->load('bad_decorates.yml');
  310. }
  311. }