PhpDumperTest.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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 PHPUnit\Framework\TestCase;
  12. use Symfony\Component\DependencyInjection\ContainerBuilder;
  13. use Symfony\Component\DependencyInjection\Definition;
  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\Variable;
  18. use Symfony\Component\ExpressionLanguage\Expression;
  19. require_once __DIR__.'/../Fixtures/includes/classes.php';
  20. class PhpDumperTest extends TestCase
  21. {
  22. protected static $fixturesPath;
  23. public static function setUpBeforeClass()
  24. {
  25. self::$fixturesPath = realpath(__DIR__.'/../Fixtures/');
  26. }
  27. public function testDump()
  28. {
  29. $dumper = new PhpDumper(new ContainerBuilder());
  30. $this->assertStringEqualsFile(self::$fixturesPath.'/php/services1.php', $dumper->dump(), '->dump() dumps an empty container as an empty PHP class');
  31. $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');
  32. }
  33. public function testDumpOptimizationString()
  34. {
  35. $definition = new Definition();
  36. $definition->setClass('stdClass');
  37. $definition->addArgument(array(
  38. 'only dot' => '.',
  39. 'concatenation as value' => '.\'\'.',
  40. 'concatenation from the start value' => '\'\'.',
  41. '.' => 'dot as a key',
  42. '.\'\'.' => 'concatenation as a key',
  43. '\'\'.' => 'concatenation from the start key',
  44. 'optimize concatenation' => 'string1%some_string%string2',
  45. 'optimize concatenation with empty string' => 'string1%empty_value%string2',
  46. 'optimize concatenation from the start' => '%empty_value%start',
  47. 'optimize concatenation at the end' => 'end%empty_value%',
  48. 'new line' => "string with \nnew line",
  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->assertStringEqualsFile(self::$fixturesPath.'/php/services9.php', str_replace(str_replace('\\', '\\\\', self::$fixturesPath.\DIRECTORY_SEPARATOR.'includes'.\DIRECTORY_SEPARATOR), '%path%', $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->assertStringEqualsFile(self::$fixturesPath.'/php/services9_compiled.php', str_replace(str_replace('\\', '\\\\', self::$fixturesPath.\DIRECTORY_SEPARATOR.'includes'.\DIRECTORY_SEPARATOR), '%path%', $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->assertStringEqualsFile(self::$fixturesPath.'/php/services20.php', str_replace(str_replace('\\', '\\\\', self::$fixturesPath.\DIRECTORY_SEPARATOR.'includes'.\DIRECTORY_SEPARATOR), '%path%', $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->assertStringEqualsFile(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 testNonSharedLazyDefinitionReferences()
  237. {
  238. $container = new ContainerBuilder();
  239. $container->register('foo', 'stdClass')->setShared(false)->setLazy(true);
  240. $container->register('bar', 'stdClass')->addArgument(new Reference('foo', ContainerBuilder::EXCEPTION_ON_INVALID_REFERENCE, false));
  241. $container->compile();
  242. $dumper = new PhpDumper($container);
  243. $dumper->setProxyDumper(new \DummyProxyDumper());
  244. $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_non_shared_lazy.php', $dumper->dump());
  245. }
  246. public function testInitializePropertiesBeforeMethodCalls()
  247. {
  248. require_once self::$fixturesPath.'/includes/classes.php';
  249. $container = new ContainerBuilder();
  250. $container->register('foo', 'stdClass');
  251. $container->register('bar', 'MethodCallClass')
  252. ->setProperty('simple', 'bar')
  253. ->setProperty('complex', new Reference('foo'))
  254. ->addMethodCall('callMe');
  255. $container->compile();
  256. $dumper = new PhpDumper($container);
  257. eval('?>'.$dumper->dump(array('class' => 'Symfony_DI_PhpDumper_Test_Properties_Before_Method_Calls')));
  258. $container = new \Symfony_DI_PhpDumper_Test_Properties_Before_Method_Calls();
  259. $this->assertTrue($container->get('bar')->callPassed(), '->dump() initializes properties before method calls');
  260. }
  261. public function testCircularReferenceAllowanceForLazyServices()
  262. {
  263. $container = new ContainerBuilder();
  264. $container->register('foo', 'stdClass')->addArgument(new Reference('bar'));
  265. $container->register('bar', 'stdClass')->setLazy(true)->addArgument(new Reference('foo'));
  266. $container->compile();
  267. $dumper = new PhpDumper($container);
  268. $dumper->dump();
  269. $this->addToAssertionCount(1);
  270. }
  271. public function testCircularReferenceAllowanceForInlinedDefinitionsForLazyServices()
  272. {
  273. /*
  274. * test graph:
  275. * [connection] -> [event_manager] --> [entity_manager](lazy)
  276. * |
  277. * --(call)- addEventListener ("@lazy_service")
  278. *
  279. * [lazy_service](lazy) -> [entity_manager](lazy)
  280. *
  281. */
  282. $container = new ContainerBuilder();
  283. $eventManagerDefinition = new Definition('stdClass');
  284. $connectionDefinition = $container->register('connection', 'stdClass');
  285. $connectionDefinition->addArgument($eventManagerDefinition);
  286. $container->register('entity_manager', 'stdClass')
  287. ->setLazy(true)
  288. ->addArgument(new Reference('connection'));
  289. $lazyServiceDefinition = $container->register('lazy_service', 'stdClass');
  290. $lazyServiceDefinition->setLazy(true);
  291. $lazyServiceDefinition->addArgument(new Reference('entity_manager'));
  292. $eventManagerDefinition->addMethodCall('addEventListener', array(new Reference('lazy_service')));
  293. $container->compile();
  294. $dumper = new PhpDumper($container);
  295. $dumper->setProxyDumper(new \DummyProxyDumper());
  296. $dumper->dump();
  297. $this->addToAssertionCount(1);
  298. }
  299. public function testDumpHandlesLiteralClassWithRootNamespace()
  300. {
  301. $container = new ContainerBuilder();
  302. $container->register('foo', '\\stdClass');
  303. $dumper = new PhpDumper($container);
  304. eval('?>'.$dumper->dump(array('class' => 'Symfony_DI_PhpDumper_Test_Literal_Class_With_Root_Namespace')));
  305. $container = new \Symfony_DI_PhpDumper_Test_Literal_Class_With_Root_Namespace();
  306. $this->assertInstanceOf('stdClass', $container->get('foo'));
  307. }
  308. /**
  309. * This test checks the trigger of a deprecation note and should not be removed in major releases.
  310. *
  311. * @group legacy
  312. * @expectedDeprecation The "foo" service is deprecated. You should stop using it, as it will soon be removed.
  313. */
  314. public function testPrivateServiceTriggersDeprecation()
  315. {
  316. $container = new ContainerBuilder();
  317. $container->register('foo', 'stdClass')
  318. ->setPublic(false)
  319. ->setDeprecated(true);
  320. $container->register('bar', 'stdClass')
  321. ->setPublic(true)
  322. ->setProperty('foo', new Reference('foo'));
  323. $container->compile();
  324. $dumper = new PhpDumper($container);
  325. eval('?>'.$dumper->dump(array('class' => 'Symfony_DI_PhpDumper_Test_Private_Service_Triggers_Deprecation')));
  326. $container = new \Symfony_DI_PhpDumper_Test_Private_Service_Triggers_Deprecation();
  327. $container->get('bar');
  328. }
  329. }