YamlFileLoaderTest.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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\ContainerBuilder;
  13. use Symfony\Component\DependencyInjection\Reference;
  14. use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
  15. use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
  16. use Symfony\Component\DependencyInjection\Loader\IniFileLoader;
  17. use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
  18. use Symfony\Component\Config\Loader\LoaderResolver;
  19. use Symfony\Component\Config\FileLocator;
  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->assertTrue(isset($services['foo']), '->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->assertTrue(isset($aliases['alias_for_foo']), '->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->assertTrue(isset($aliases['another_alias_for_foo']));
  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->assertTrue(isset($services['project.service.bar']), '->load() parses extension elements');
  174. $this->assertTrue(isset($parameters['project.parameter.bar']), '->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 testSupports()
  186. {
  187. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator());
  188. $this->assertTrue($loader->supports('foo.yml'), '->supports() returns true if the resource is loadable');
  189. $this->assertTrue($loader->supports('foo.yaml'), '->supports() returns true if the resource is loadable');
  190. $this->assertFalse($loader->supports('foo.foo'), '->supports() returns true if the resource is loadable');
  191. }
  192. public function testNonArrayTagsThrowsException()
  193. {
  194. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  195. try {
  196. $loader->load('badtag1.yml');
  197. $this->fail('->load() should throw an exception when the tags key of a service is not an array');
  198. } catch (\Exception $e) {
  199. $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the tags key is not an array');
  200. $this->assertStringStartsWith('Parameter "tags" must be an array for service', $e->getMessage(), '->load() throws an InvalidArgumentException if the tags key is not an array');
  201. }
  202. }
  203. /**
  204. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  205. * @expectedExceptionMessage A "tags" entry must be an array for service
  206. */
  207. public function testNonArrayTagThrowsException()
  208. {
  209. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  210. $loader->load('badtag4.yml');
  211. }
  212. public function testTagWithoutNameThrowsException()
  213. {
  214. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  215. try {
  216. $loader->load('badtag2.yml');
  217. $this->fail('->load() should throw an exception when a tag is missing the name key');
  218. } catch (\Exception $e) {
  219. $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if a tag is missing the name key');
  220. $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');
  221. }
  222. }
  223. public function testTagWithAttributeArrayThrowsException()
  224. {
  225. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  226. try {
  227. $loader->load('badtag3.yml');
  228. $this->fail('->load() should throw an exception when a tag-attribute is not a scalar');
  229. } catch (\Exception $e) {
  230. $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if a tag-attribute is not a scalar');
  231. $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');
  232. }
  233. }
  234. public function testLoadYamlOnlyWithKeys()
  235. {
  236. $container = new ContainerBuilder();
  237. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  238. $loader->load('services21.yml');
  239. $definition = $container->getDefinition('manager');
  240. $this->assertEquals(array(array('setLogger', array(new Reference('logger'))), array('setClass', array('User'))), $definition->getMethodCalls());
  241. $this->assertEquals(array(true), $definition->getArguments());
  242. $this->assertEquals(array('manager' => array(array('alias' => 'user'))), $definition->getTags());
  243. }
  244. /**
  245. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  246. * @expectedExceptionMessageRegExp /The tag name for service ".+" in .+ must be a non-empty string/
  247. */
  248. public function testTagWithEmptyNameThrowsException()
  249. {
  250. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  251. $loader->load('tag_name_empty_string.yml');
  252. }
  253. /**
  254. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  255. * @expectedExceptionMessageREgExp /The tag name for service "\.+" must be a non-empty string/
  256. */
  257. public function testTagWithNonStringNameThrowsException()
  258. {
  259. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  260. $loader->load('tag_name_no_string.yml');
  261. }
  262. /**
  263. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  264. */
  265. public function testTypesNotArray()
  266. {
  267. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  268. $loader->load('bad_types1.yml');
  269. }
  270. /**
  271. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  272. */
  273. public function testTypeNotString()
  274. {
  275. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  276. $loader->load('bad_types2.yml');
  277. }
  278. public function testTypes()
  279. {
  280. $container = new ContainerBuilder();
  281. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  282. $loader->load('services22.yml');
  283. $this->assertEquals(array('Foo', 'Bar'), $container->getDefinition('foo_service')->getAutowiringTypes());
  284. $this->assertEquals(array('Foo'), $container->getDefinition('baz_service')->getAutowiringTypes());
  285. }
  286. public function testAutowire()
  287. {
  288. $container = new ContainerBuilder();
  289. $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
  290. $loader->load('services23.yml');
  291. $this->assertTrue($container->getDefinition('bar_service')->isAutowired());
  292. }
  293. /**
  294. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  295. * @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").
  296. */
  297. public function testDecoratedServicesWithWrongSyntaxThrowsException()
  298. {
  299. $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
  300. $loader->load('bad_decorates.yml');
  301. }
  302. }