PhpDumperTest.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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\Dumper;
  11. use DummyProxyDumper;
  12. use PHPUnit\Framework\TestCase;
  13. use Symfony\Component\DependencyInjection\ContainerBuilder;
  14. use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
  15. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
  16. use Symfony\Component\DependencyInjection\Reference;
  17. use Symfony\Component\DependencyInjection\Definition;
  18. use Symfony\Component\DependencyInjection\Variable;
  19. use Symfony\Component\ExpressionLanguage\Expression;
  20. require_once __DIR__.'/../Fixtures/includes/classes.php';
  21. class PhpDumperTest extends TestCase
  22. {
  23. protected static $fixturesPath;
  24. public static function setUpBeforeClass()
  25. {
  26. self::$fixturesPath = realpath(__DIR__.'/../Fixtures/');
  27. }
  28. public function testDump()
  29. {
  30. $dumper = new PhpDumper(new ContainerBuilder());
  31. $this->assertStringEqualsFile(self::$fixturesPath.'/php/services1.php', $dumper->dump(), '->dump() dumps an empty container as an empty PHP class');
  32. $this->assertStringEqualsFile(self::$fixturesPath.'/php/services1-1.php', $dumper->dump(array('class' => 'Container', 'base_class' => 'AbstractContainer', 'namespace' => 'Symfony\Component\DependencyInjection\Dump')), '->dump() takes a class and a base_class options');
  33. }
  34. public function testDumpOptimizationString()
  35. {
  36. $definition = new Definition();
  37. $definition->setClass('stdClass');
  38. $definition->addArgument(array(
  39. 'only dot' => '.',
  40. 'concatenation as value' => '.\'\'.',
  41. 'concatenation from the start value' => '\'\'.',
  42. '.' => 'dot as a key',
  43. '.\'\'.' => 'concatenation as a key',
  44. '\'\'.' => 'concatenation from the start key',
  45. 'optimize concatenation' => 'string1%some_string%string2',
  46. 'optimize concatenation with empty string' => 'string1%empty_value%string2',
  47. 'optimize concatenation from the start' => '%empty_value%start',
  48. 'optimize concatenation at the end' => 'end%empty_value%',
  49. ));
  50. $container = new ContainerBuilder();
  51. $container->setResourceTracking(false);
  52. $container->setDefinition('test', $definition);
  53. $container->setParameter('empty_value', '');
  54. $container->setParameter('some_string', '-');
  55. $container->compile();
  56. $dumper = new PhpDumper($container);
  57. $this->assertStringEqualsFile(self::$fixturesPath.'/php/services10.php', $dumper->dump(), '->dump() dumps an empty container as an empty PHP class');
  58. }
  59. public function testDumpRelativeDir()
  60. {
  61. $definition = new Definition();
  62. $definition->setClass('stdClass');
  63. $definition->addArgument('%foo%');
  64. $definition->addArgument(array('%foo%' => '%buz%/'));
  65. $container = new ContainerBuilder();
  66. $container->setDefinition('test', $definition);
  67. $container->setParameter('foo', 'wiz'.dirname(__DIR__));
  68. $container->setParameter('bar', __DIR__);
  69. $container->setParameter('baz', '%bar%/PhpDumperTest.php');
  70. $container->setParameter('buz', dirname(dirname(__DIR__)));
  71. $container->compile();
  72. $dumper = new PhpDumper($container);
  73. $this->assertStringEqualsFile(self::$fixturesPath.'/php/services12.php', $dumper->dump(array('file' => __FILE__)), '->dump() dumps __DIR__ relative strings');
  74. }
  75. /**
  76. * @dataProvider provideInvalidParameters
  77. * @expectedException \InvalidArgumentException
  78. */
  79. public function testExportParameters($parameters)
  80. {
  81. $dumper = new PhpDumper(new ContainerBuilder(new ParameterBag($parameters)));
  82. $dumper->dump();
  83. }
  84. public function provideInvalidParameters()
  85. {
  86. return array(
  87. array(array('foo' => new Definition('stdClass'))),
  88. array(array('foo' => new Expression('service("foo").foo() ~ (container.hasParameter("foo") ? parameter("foo") : "default")'))),
  89. array(array('foo' => new Reference('foo'))),
  90. array(array('foo' => new Variable('foo'))),
  91. );
  92. }
  93. public function testAddParameters()
  94. {
  95. $container = include self::$fixturesPath.'/containers/container8.php';
  96. $dumper = new PhpDumper($container);
  97. $this->assertStringEqualsFile(self::$fixturesPath.'/php/services8.php', $dumper->dump(), '->dump() dumps parameters');
  98. }
  99. public function testAddService()
  100. {
  101. // without compilation
  102. $container = include self::$fixturesPath.'/containers/container9.php';
  103. $dumper = new PhpDumper($container);
  104. $this->assertEquals(str_replace('%path%', str_replace('\\', '\\\\', self::$fixturesPath.DIRECTORY_SEPARATOR.'includes'.DIRECTORY_SEPARATOR), file_get_contents(self::$fixturesPath.'/php/services9.php')), $dumper->dump(), '->dump() dumps services');
  105. // with compilation
  106. $container = include self::$fixturesPath.'/containers/container9.php';
  107. $container->compile();
  108. $dumper = new PhpDumper($container);
  109. $this->assertEquals(str_replace('%path%', str_replace('\\', '\\\\', self::$fixturesPath.DIRECTORY_SEPARATOR.'includes'.DIRECTORY_SEPARATOR), file_get_contents(self::$fixturesPath.'/php/services9_compiled.php')), $dumper->dump(), '->dump() dumps services');
  110. $dumper = new PhpDumper($container = new ContainerBuilder());
  111. $container->register('foo', 'FooClass')->addArgument(new \stdClass());
  112. try {
  113. $dumper->dump();
  114. $this->fail('->dump() throws a RuntimeException if the container to be dumped has reference to objects or resources');
  115. } catch (\Exception $e) {
  116. $this->assertInstanceOf('\Symfony\Component\DependencyInjection\Exception\RuntimeException', $e, '->dump() throws a RuntimeException if the container to be dumped has reference to objects or resources');
  117. $this->assertEquals('Unable to dump a service container if a parameter is an object or a resource.', $e->getMessage(), '->dump() throws a RuntimeException if the container to be dumped has reference to objects or resources');
  118. }
  119. }
  120. /**
  121. * @group legacy
  122. */
  123. public function testLegacySynchronizedServices()
  124. {
  125. $container = include self::$fixturesPath.'/containers/container20.php';
  126. $dumper = new PhpDumper($container);
  127. $this->assertEquals(str_replace('%path%', str_replace('\\', '\\\\', self::$fixturesPath.DIRECTORY_SEPARATOR.'includes'.DIRECTORY_SEPARATOR), file_get_contents(self::$fixturesPath.'/php/services20.php')), $dumper->dump(), '->dump() dumps services');
  128. }
  129. public function testServicesWithAnonymousFactories()
  130. {
  131. $container = include self::$fixturesPath.'/containers/container19.php';
  132. $dumper = new PhpDumper($container);
  133. $this->assertStringEqualsFile(self::$fixturesPath.'/php/services19.php', $dumper->dump(), '->dump() dumps services with anonymous factories');
  134. }
  135. /**
  136. * @expectedException \InvalidArgumentException
  137. * @expectedExceptionMessage Service id "bar$" cannot be converted to a valid PHP method name.
  138. */
  139. public function testAddServiceInvalidServiceId()
  140. {
  141. $container = new ContainerBuilder();
  142. $container->register('bar$', 'FooClass');
  143. $dumper = new PhpDumper($container);
  144. $dumper->dump();
  145. }
  146. /**
  147. * @dataProvider provideInvalidFactories
  148. * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException
  149. * @expectedExceptionMessage Cannot dump definition
  150. */
  151. public function testInvalidFactories($factory)
  152. {
  153. $container = new ContainerBuilder();
  154. $def = new Definition('stdClass');
  155. $def->setFactory($factory);
  156. $container->setDefinition('bar', $def);
  157. $dumper = new PhpDumper($container);
  158. $dumper->dump();
  159. }
  160. public function provideInvalidFactories()
  161. {
  162. return array(
  163. array(array('', 'method')),
  164. array(array('class', '')),
  165. array(array('...', 'method')),
  166. array(array('class', '...')),
  167. );
  168. }
  169. public function testAliases()
  170. {
  171. $container = include self::$fixturesPath.'/containers/container9.php';
  172. $container->compile();
  173. $dumper = new PhpDumper($container);
  174. eval('?>'.$dumper->dump(array('class' => 'Symfony_DI_PhpDumper_Test_Aliases')));
  175. $container = new \Symfony_DI_PhpDumper_Test_Aliases();
  176. $container->set('foo', $foo = new \stdClass());
  177. $this->assertSame($foo, $container->get('foo'));
  178. $this->assertSame($foo, $container->get('alias_for_foo'));
  179. $this->assertSame($foo, $container->get('alias_for_alias'));
  180. }
  181. public function testFrozenContainerWithoutAliases()
  182. {
  183. $container = new ContainerBuilder();
  184. $container->compile();
  185. $dumper = new PhpDumper($container);
  186. eval('?>'.$dumper->dump(array('class' => 'Symfony_DI_PhpDumper_Test_Frozen_No_Aliases')));
  187. $container = new \Symfony_DI_PhpDumper_Test_Frozen_No_Aliases();
  188. $this->assertFalse($container->has('foo'));
  189. }
  190. public function testOverrideServiceWhenUsingADumpedContainer()
  191. {
  192. require_once self::$fixturesPath.'/php/services9.php';
  193. require_once self::$fixturesPath.'/includes/foo.php';
  194. $container = new \ProjectServiceContainer();
  195. $container->set('bar', $bar = new \stdClass());
  196. $container->setParameter('foo_bar', 'foo_bar');
  197. $this->assertSame($bar, $container->get('bar'), '->set() overrides an already defined service');
  198. }
  199. public function testOverrideServiceWhenUsingADumpedContainerAndServiceIsUsedFromAnotherOne()
  200. {
  201. require_once self::$fixturesPath.'/php/services9.php';
  202. require_once self::$fixturesPath.'/includes/foo.php';
  203. require_once self::$fixturesPath.'/includes/classes.php';
  204. $container = new \ProjectServiceContainer();
  205. $container->set('bar', $bar = new \stdClass());
  206. $this->assertSame($bar, $container->get('foo')->bar, '->set() overrides an already defined service');
  207. }
  208. /**
  209. * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException
  210. */
  211. public function testCircularReference()
  212. {
  213. $container = new ContainerBuilder();
  214. $container->register('foo', 'stdClass')->addArgument(new Reference('bar'));
  215. $container->register('bar', 'stdClass')->setPublic(false)->addMethodCall('setA', array(new Reference('baz')));
  216. $container->register('baz', 'stdClass')->addMethodCall('setA', array(new Reference('foo')));
  217. $container->compile();
  218. $dumper = new PhpDumper($container);
  219. $dumper->dump();
  220. }
  221. public function testDumpAutowireData()
  222. {
  223. $container = include self::$fixturesPath.'/containers/container24.php';
  224. $dumper = new PhpDumper($container);
  225. $this->assertEquals(file_get_contents(self::$fixturesPath.'/php/services24.php'), $dumper->dump());
  226. }
  227. public function testInlinedDefinitionReferencingServiceContainer()
  228. {
  229. $container = new ContainerBuilder();
  230. $container->register('foo', 'stdClass')->addMethodCall('add', array(new Reference('service_container')))->setPublic(false);
  231. $container->register('bar', 'stdClass')->addArgument(new Reference('foo'));
  232. $container->compile();
  233. $dumper = new PhpDumper($container);
  234. $this->assertStringEqualsFile(self::$fixturesPath.'/php/services13.php', $dumper->dump(), '->dump() dumps inline definitions which reference service_container');
  235. }
  236. public function testInitializePropertiesBeforeMethodCalls()
  237. {
  238. require_once self::$fixturesPath.'/includes/classes.php';
  239. $container = new ContainerBuilder();
  240. $container->register('foo', 'stdClass');
  241. $container->register('bar', 'MethodCallClass')
  242. ->setProperty('simple', 'bar')
  243. ->setProperty('complex', new Reference('foo'))
  244. ->addMethodCall('callMe');
  245. $container->compile();
  246. $dumper = new PhpDumper($container);
  247. eval('?>'.$dumper->dump(array('class' => 'Symfony_DI_PhpDumper_Test_Properties_Before_Method_Calls')));
  248. $container = new \Symfony_DI_PhpDumper_Test_Properties_Before_Method_Calls();
  249. $this->assertTrue($container->get('bar')->callPassed(), '->dump() initializes properties before method calls');
  250. }
  251. public function testCircularReferenceAllowanceForLazyServices()
  252. {
  253. $container = new ContainerBuilder();
  254. $container->register('foo', 'stdClass')->addArgument(new Reference('bar'));
  255. $container->register('bar', 'stdClass')->setLazy(true)->addArgument(new Reference('foo'));
  256. $container->compile();
  257. $dumper = new PhpDumper($container);
  258. $dumper->dump();
  259. $this->addToAssertionCount(1);
  260. }
  261. public function testCircularReferenceAllowanceForInlinedDefinitionsForLazyServices()
  262. {
  263. /*
  264. * test graph:
  265. * [connection] -> [event_manager] --> [entity_manager](lazy)
  266. * |
  267. * --(call)- addEventListener ("@lazy_service")
  268. *
  269. * [lazy_service](lazy) -> [entity_manager](lazy)
  270. *
  271. */
  272. $container = new ContainerBuilder();
  273. $eventManagerDefinition = new Definition('stdClass');
  274. $connectionDefinition = $container->register('connection', 'stdClass');
  275. $connectionDefinition->addArgument($eventManagerDefinition);
  276. $container->register('entity_manager', 'stdClass')
  277. ->setLazy(true)
  278. ->addArgument(new Reference('connection'));
  279. $lazyServiceDefinition = $container->register('lazy_service', 'stdClass');
  280. $lazyServiceDefinition->setLazy(true);
  281. $lazyServiceDefinition->addArgument(new Reference('entity_manager'));
  282. $eventManagerDefinition->addMethodCall('addEventListener', array(new Reference('lazy_service')));
  283. $container->compile();
  284. $dumper = new PhpDumper($container);
  285. $dumper->setProxyDumper(new DummyProxyDumper());
  286. $dumper->dump();
  287. $this->addToAssertionCount(1);
  288. }
  289. }