XmlFileLoaderTest.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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\Tests\Component\DependencyInjection\Loader;
  11. use Symfony\Component\DependencyInjection\ContainerInterface;
  12. use Symfony\Component\DependencyInjection\ContainerBuilder;
  13. use Symfony\Component\DependencyInjection\Reference;
  14. use Symfony\Component\DependencyInjection\Definition;
  15. use Symfony\Component\Config\Loader\Loader;
  16. use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
  17. use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
  18. use Symfony\Component\DependencyInjection\Loader\IniFileLoader;
  19. use Symfony\Component\Config\Loader\LoaderResolver;
  20. use Symfony\Component\Config\FileLocator;
  21. class XmlFileLoaderTest extends \PHPUnit_Framework_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. require_once self::$fixturesPath.'/includes/ProjectWithXsdExtension.php';
  30. }
  31. public function testLoad()
  32. {
  33. $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/ini'));
  34. try {
  35. $loader->load('foo.xml');
  36. $this->fail('->load() throws an InvalidArgumentException if the loaded file does not exist');
  37. } catch (\Exception $e) {
  38. $this->assertInstanceOf('\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the loaded file does not exist');
  39. $this->assertStringStartsWith('The file "foo.xml" does not exist (in:', $e->getMessage(), '->load() throws an InvalidArgumentException if the loaded file does not exist');
  40. }
  41. }
  42. public function testParseFile()
  43. {
  44. $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/ini'));
  45. $r = new \ReflectionObject($loader);
  46. $m = $r->getMethod('parseFile');
  47. $m->setAccessible(true);
  48. try {
  49. $m->invoke($loader, self::$fixturesPath.'/ini/parameters.ini');
  50. $this->fail('->parseFile() throws an InvalidArgumentException if the loaded file is not a valid XML file');
  51. } catch (\Exception $e) {
  52. $this->assertInstanceOf('\InvalidArgumentException', $e, '->parseFile() throws an InvalidArgumentException if the loaded file is not a valid XML file');
  53. $this->assertStringStartsWith('[ERROR 4] Start tag expected, \'<\' not found (in', $e->getMessage(), '->parseFile() throws an InvalidArgumentException if the loaded file is not a valid XML file');
  54. }
  55. $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/xml'));
  56. try {
  57. $m->invoke($loader, self::$fixturesPath.'/xml/nonvalid.xml');
  58. $this->fail('->parseFile() throws an InvalidArgumentException if the loaded file does not validate the XSD');
  59. } catch (\Exception $e) {
  60. $this->assertInstanceOf('\InvalidArgumentException', $e, '->parseFile() throws an InvalidArgumentException if the loaded file does not validate the XSD');
  61. $this->assertStringStartsWith('[ERROR 1845] Element \'nonvalid\': No matching global declaration available for the validation root. (in', $e->getMessage(), '->parseFile() throws an InvalidArgumentException if the loaded file does not validate the XSD');
  62. }
  63. $xml = $m->invoke($loader, self::$fixturesPath.'/xml/services1.xml');
  64. $this->assertEquals('Symfony\\Component\\DependencyInjection\\SimpleXMLElement', get_class($xml), '->parseFile() returns an SimpleXMLElement object');
  65. }
  66. public function testLoadParameters()
  67. {
  68. $container = new ContainerBuilder();
  69. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  70. $loader->load('services2.xml');
  71. $actual = $container->getParameterBag()->all();
  72. $expected = array('a string', 'foo' => 'bar', 'values' => array(0, 'integer' => 4, 100 => null, 'true', true, false, 'on', 'off', 'float' => 1.3, 1000.3, 'a string', array('foo', 'bar')), 'foo_bar' => new Reference('foo_bar'), 'mixedcase' => array('MixedCaseKey' => 'value'));
  73. $this->assertEquals($expected, $actual, '->load() converts XML values to PHP ones');
  74. }
  75. public function testLoadImports()
  76. {
  77. $container = new ContainerBuilder();
  78. $resolver = new LoaderResolver(array(
  79. new IniFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')),
  80. new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')),
  81. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')),
  82. ));
  83. $loader->setResolver($resolver);
  84. $loader->load('services4.xml');
  85. $actual = $container->getParameterBag()->all();
  86. $expected = array('a string', 'foo' => 'bar', 'values' => array(true, false), 'foo_bar' => new Reference('foo_bar'), 'mixedcase' => array('MixedCaseKey' => 'value'), 'bar' => '%foo%', 'imported_from_ini' => true, 'imported_from_yaml' => true);
  87. $this->assertEquals(array_keys($expected), array_keys($actual), '->load() imports and merges imported files');
  88. // Bad import throws no exception due to ignore_errors value.
  89. $loader->load('services4_bad_import.xml');
  90. }
  91. public function testLoadAnonymousServices()
  92. {
  93. $container = new ContainerBuilder();
  94. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  95. $loader->load('services5.xml');
  96. $services = $container->getDefinitions();
  97. $this->assertEquals(3, count($services), '->load() attributes unique ids to anonymous services');
  98. $args = $services['foo']->getArguments();
  99. $this->assertEquals(1, count($args), '->load() references anonymous services as "normal" ones');
  100. $this->assertEquals('Symfony\\Component\\DependencyInjection\\Reference', get_class($args[0]), '->load() converts anonymous services to references to "normal" services');
  101. $this->assertTrue(isset($services[(string) $args[0]]), '->load() makes a reference to the created ones');
  102. $inner = $services[(string) $args[0]];
  103. $this->assertEquals('BarClass', $inner->getClass(), '->load() uses the same configuration as for the anonymous ones');
  104. $args = $inner->getArguments();
  105. $this->assertEquals(1, count($args), '->load() references anonymous services as "normal" ones');
  106. $this->assertEquals('Symfony\\Component\\DependencyInjection\\Reference', get_class($args[0]), '->load() converts anonymous services to references to "normal" services');
  107. $this->assertTrue(isset($services[(string) $args[0]]), '->load() makes a reference to the created ones');
  108. $inner = $services[(string) $args[0]];
  109. $this->assertEquals('BazClass', $inner->getClass(), '->load() uses the same configuration as for the anonymous ones');
  110. }
  111. public function testLoadServices()
  112. {
  113. $container = new ContainerBuilder();
  114. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  115. $loader->load('services6.xml');
  116. $services = $container->getDefinitions();
  117. $this->assertTrue(isset($services['foo']), '->load() parses <service> elements');
  118. $this->assertEquals('Symfony\\Component\\DependencyInjection\\Definition', get_class($services['foo']), '->load() converts <service> element to Definition instances');
  119. $this->assertEquals('FooClass', $services['foo']->getClass(), '->load() parses the class attribute');
  120. $this->assertEquals('container', $services['scope.container']->getScope());
  121. $this->assertEquals('custom', $services['scope.custom']->getScope());
  122. $this->assertEquals('prototype', $services['scope.prototype']->getScope());
  123. $this->assertEquals('getInstance', $services['constructor']->getFactoryMethod(), '->load() parses the factory-method attribute');
  124. $this->assertEquals('%path%/foo.php', $services['file']->getFile(), '->load() parses the file tag');
  125. $this->assertEquals(array('foo', new Reference('foo'), array(true, false)), $services['arguments']->getArguments(), '->load() parses the argument tags');
  126. $this->assertEquals('sc_configure', $services['configurator1']->getConfigurator(), '->load() parses the configurator tag');
  127. $this->assertEquals(array(new Reference('baz', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, false), 'configure'), $services['configurator2']->getConfigurator(), '->load() parses the configurator tag');
  128. $this->assertEquals(array('BazClass', 'configureStatic'), $services['configurator3']->getConfigurator(), '->load() parses the configurator tag');
  129. $this->assertEquals(array(array('setBar', array())), $services['method_call1']->getMethodCalls(), '->load() parses the method_call tag');
  130. $this->assertEquals(array(array('setBar', array('foo', new Reference('foo'), array(true, false)))), $services['method_call2']->getMethodCalls(), '->load() parses the method_call tag');
  131. $this->assertNull($services['factory_service']->getClass());
  132. $this->assertEquals('getInstance', $services['factory_service']->getFactoryMethod());
  133. $this->assertEquals('baz_factory', $services['factory_service']->getFactoryService());
  134. $aliases = $container->getAliases();
  135. $this->assertTrue(isset($aliases['alias_for_foo']), '->load() parses <service> elements');
  136. $this->assertEquals('foo', (string) $aliases['alias_for_foo'], '->load() parses aliases');
  137. $this->assertTrue($aliases['alias_for_foo']->isPublic());
  138. $this->assertTrue(isset($aliases['another_alias_for_foo']));
  139. $this->assertEquals('foo', (string) $aliases['another_alias_for_foo']);
  140. $this->assertFalse($aliases['another_alias_for_foo']->isPublic());
  141. }
  142. public function testConvertDomElementToArray()
  143. {
  144. $doc = new \DOMDocument("1.0");
  145. $doc->loadXML('<foo>bar</foo>');
  146. $this->assertEquals('bar', XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
  147. $doc = new \DOMDocument("1.0");
  148. $doc->loadXML('<foo foo="bar" />');
  149. $this->assertEquals(array('foo' => 'bar'), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
  150. $doc = new \DOMDocument("1.0");
  151. $doc->loadXML('<foo><foo>bar</foo></foo>');
  152. $this->assertEquals(array('foo' => 'bar'), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
  153. $doc = new \DOMDocument("1.0");
  154. $doc->loadXML('<foo><foo>bar<foo>bar</foo></foo></foo>');
  155. $this->assertEquals(array('foo' => array('value' => 'bar', 'foo' => 'bar')), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
  156. $doc = new \DOMDocument("1.0");
  157. $doc->loadXML('<foo><foo></foo></foo>');
  158. $this->assertEquals(array('foo' => null), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
  159. $doc = new \DOMDocument("1.0");
  160. $doc->loadXML('<foo><foo><!-- foo --></foo></foo>');
  161. $this->assertEquals(array('foo' => null), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
  162. $doc = new \DOMDocument("1.0");
  163. $doc->loadXML('<foo><foo foo="bar"/><foo foo="bar"/></foo>');
  164. $this->assertEquals(array('foo' => array(array('foo' => 'bar'), array('foo' => 'bar'))), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
  165. }
  166. public function testExtensions()
  167. {
  168. $container = new ContainerBuilder();
  169. $container->registerExtension(new \ProjectExtension());
  170. $container->registerExtension(new \ProjectWithXsdExtension());
  171. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  172. // extension without an XSD
  173. $loader->load('extensions/services1.xml');
  174. $container->compile();
  175. $services = $container->getDefinitions();
  176. $parameters = $container->getParameterBag()->all();
  177. $this->assertTrue(isset($services['project.service.bar']), '->load() parses extension elements');
  178. $this->assertTrue(isset($parameters['project.parameter.bar']), '->load() parses extension elements');
  179. $this->assertEquals('BAR', $services['project.service.foo']->getClass(), '->load() parses extension elements');
  180. $this->assertEquals('BAR', $parameters['project.parameter.foo'], '->load() parses extension elements');
  181. // extension with an XSD
  182. $container = new ContainerBuilder();
  183. $container->registerExtension(new \ProjectExtension());
  184. $container->registerExtension(new \ProjectWithXsdExtension());
  185. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  186. $loader->load('extensions/services2.xml');
  187. $container->compile();
  188. $services = $container->getDefinitions();
  189. $parameters = $container->getParameterBag()->all();
  190. $this->assertTrue(isset($services['project.service.bar']), '->load() parses extension elements');
  191. $this->assertTrue(isset($parameters['project.parameter.bar']), '->load() parses extension elements');
  192. $this->assertEquals('BAR', $services['project.service.foo']->getClass(), '->load() parses extension elements');
  193. $this->assertEquals('BAR', $parameters['project.parameter.foo'], '->load() parses extension elements');
  194. $container = new ContainerBuilder();
  195. $container->registerExtension(new \ProjectExtension());
  196. $container->registerExtension(new \ProjectWithXsdExtension());
  197. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  198. // extension with an XSD (does not validate)
  199. try {
  200. $loader->load('extensions/services3.xml');
  201. $this->fail('->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
  202. } catch (\Exception $e) {
  203. $this->assertInstanceOf('\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
  204. $this->assertRegexp('/The attribute \'bar\' is not allowed/', $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
  205. }
  206. // non-registered extension
  207. try {
  208. $loader->load('extensions/services4.xml');
  209. $this->fail('->load() throws an InvalidArgumentException if the tag is not valid');
  210. } catch (\Exception $e) {
  211. $this->assertInstanceOf('\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the tag is not valid');
  212. $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');
  213. }
  214. }
  215. public function testExtensionInPhar()
  216. {
  217. if (extension_loaded('suhosin') && false === strpos(ini_get('suhosin.executor.include.whitelist'), 'phar')) {
  218. $this->markTestSkipped('To run this test, add "phar" to the "suhosin.executor.include.whitelist" settings in your php.ini file.');
  219. }
  220. require_once self::$fixturesPath.'/includes/ProjectWithXsdExtensionInPhar.phar';
  221. // extension with an XSD in PHAR archive
  222. $container = new ContainerBuilder();
  223. $container->registerExtension(new \ProjectWithXsdExtensionInPhar());
  224. $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  225. $loader->load('extensions/services6.xml');
  226. // extension with an XSD in PHAR archive (does not validate)
  227. try {
  228. $loader->load('extensions/services7.xml');
  229. $this->fail('->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
  230. } catch (\Exception $e) {
  231. $this->assertInstanceOf('\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
  232. $this->assertRegexp('/The attribute \'bar\' is not allowed/', $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
  233. }
  234. }
  235. /**
  236. * @covers Symfony\Component\DependencyInjection\Loader\XmlFileLoader::supports
  237. */
  238. public function testSupports()
  239. {
  240. $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator());
  241. $this->assertTrue($loader->supports('foo.xml'), '->supports() returns true if the resource is loadable');
  242. $this->assertFalse($loader->supports('foo.foo'), '->supports() returns true if the resource is loadable');
  243. }
  244. public function testNoNamingConflictsForAnonymousServices()
  245. {
  246. $container = new ContainerBuilder();
  247. $loader1 = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml/extension1'));
  248. $loader1->load('services.xml');
  249. $services = $container->getDefinitions();
  250. $this->assertEquals(2, count($services), '->load() attributes unique ids to anonymous services');
  251. $loader2 = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml/extension2'));
  252. $loader2->load('services.xml');
  253. $services = $container->getDefinitions();
  254. $this->assertEquals(4, count($services), '->load() attributes unique ids to anonymous services');
  255. $services = $container->getDefinitions();
  256. $args1 = $services['extension1.foo']->getArguments();
  257. $inner1 = $services[(string) $args1[0]];
  258. $this->assertEquals('BarClass1', $inner1->getClass(), '->load() uses the same configuration as for the anonymous ones');
  259. $args2 = $services['extension2.foo']->getArguments();
  260. $inner2 = $services[(string) $args2[0]];
  261. $this->assertEquals('BarClass2', $inner2->getClass(), '->load() uses the same configuration as for the anonymous ones');
  262. }
  263. /**
  264. * @expectedException \InvalidArgumentException
  265. * @expectedExceptionMessage Document types are not allowed.
  266. */
  267. public function testDocTypeIsNotAllowed()
  268. {
  269. $container = new ContainerBuilder();
  270. $loader1 = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
  271. $loader1->load('withdoctype.xml');
  272. }
  273. }