ContainerBuilderTest.php 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  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;
  11. require_once __DIR__.'/Fixtures/includes/classes.php';
  12. require_once __DIR__.'/Fixtures/includes/ProjectExtension.php';
  13. use PHPUnit\Framework\TestCase;
  14. use Symfony\Component\Config\Resource\FileResource;
  15. use Symfony\Component\Config\Resource\ResourceInterface;
  16. use Symfony\Component\DependencyInjection\Alias;
  17. use Symfony\Component\DependencyInjection\ContainerBuilder;
  18. use Symfony\Component\DependencyInjection\ContainerInterface;
  19. use Symfony\Component\DependencyInjection\Definition;
  20. use Symfony\Component\DependencyInjection\DefinitionDecorator;
  21. use Symfony\Component\DependencyInjection\Exception\InactiveScopeException;
  22. use Symfony\Component\DependencyInjection\Exception\RuntimeException;
  23. use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
  24. use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
  25. use Symfony\Component\DependencyInjection\Loader\ClosureLoader;
  26. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
  27. use Symfony\Component\DependencyInjection\Reference;
  28. use Symfony\Component\DependencyInjection\Scope;
  29. use Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition;
  30. use Symfony\Component\ExpressionLanguage\Expression;
  31. class ContainerBuilderTest extends TestCase
  32. {
  33. public function testDefinitions()
  34. {
  35. $builder = new ContainerBuilder();
  36. $definitions = array(
  37. 'foo' => new Definition('Bar\FooClass'),
  38. 'bar' => new Definition('BarClass'),
  39. );
  40. $builder->setDefinitions($definitions);
  41. $this->assertEquals($definitions, $builder->getDefinitions(), '->setDefinitions() sets the service definitions');
  42. $this->assertTrue($builder->hasDefinition('foo'), '->hasDefinition() returns true if a service definition exists');
  43. $this->assertFalse($builder->hasDefinition('foobar'), '->hasDefinition() returns false if a service definition does not exist');
  44. $builder->setDefinition('foobar', $foo = new Definition('FooBarClass'));
  45. $this->assertEquals($foo, $builder->getDefinition('foobar'), '->getDefinition() returns a service definition if defined');
  46. $this->assertSame($builder->setDefinition('foobar', $foo = new Definition('FooBarClass')), $foo, '->setDefinition() implements a fluid interface by returning the service reference');
  47. $builder->addDefinitions($defs = array('foobar' => new Definition('FooBarClass')));
  48. $this->assertEquals(array_merge($definitions, $defs), $builder->getDefinitions(), '->addDefinitions() adds the service definitions');
  49. try {
  50. $builder->getDefinition('baz');
  51. $this->fail('->getDefinition() throws a ServiceNotFoundException if the service definition does not exist');
  52. } catch (ServiceNotFoundException $e) {
  53. $this->assertEquals('You have requested a non-existent service "baz".', $e->getMessage(), '->getDefinition() throws a ServiceNotFoundException if the service definition does not exist');
  54. }
  55. }
  56. /**
  57. * @group legacy
  58. * @expectedDeprecation The "deprecated_foo" service is deprecated. You should stop using it, as it will soon be removed.
  59. */
  60. public function testCreateDeprecatedService()
  61. {
  62. $definition = new Definition('stdClass');
  63. $definition->setDeprecated(true);
  64. $builder = new ContainerBuilder();
  65. $builder->createService($definition, new \SplObjectStorage(), 'deprecated_foo');
  66. }
  67. public function testRegister()
  68. {
  69. $builder = new ContainerBuilder();
  70. $builder->register('foo', 'Bar\FooClass');
  71. $this->assertTrue($builder->hasDefinition('foo'), '->register() registers a new service definition');
  72. $this->assertInstanceOf('Symfony\Component\DependencyInjection\Definition', $builder->getDefinition('foo'), '->register() returns the newly created Definition instance');
  73. }
  74. public function testHas()
  75. {
  76. $builder = new ContainerBuilder();
  77. $this->assertFalse($builder->has('foo'), '->has() returns false if the service does not exist');
  78. $builder->register('foo', 'Bar\FooClass');
  79. $this->assertTrue($builder->has('foo'), '->has() returns true if a service definition exists');
  80. $builder->set('bar', new \stdClass());
  81. $this->assertTrue($builder->has('bar'), '->has() returns true if a service exists');
  82. }
  83. public function testGet()
  84. {
  85. $builder = new ContainerBuilder();
  86. try {
  87. $builder->get('foo');
  88. $this->fail('->get() throws a ServiceNotFoundException if the service does not exist');
  89. } catch (ServiceNotFoundException $e) {
  90. $this->assertEquals('You have requested a non-existent service "foo".', $e->getMessage(), '->get() throws a ServiceNotFoundException if the service does not exist');
  91. }
  92. $this->assertNull($builder->get('foo', ContainerInterface::NULL_ON_INVALID_REFERENCE), '->get() returns null if the service does not exist and NULL_ON_INVALID_REFERENCE is passed as a second argument');
  93. $builder->register('foo', 'stdClass');
  94. $this->assertInternalType('object', $builder->get('foo'), '->get() returns the service definition associated with the id');
  95. $builder->set('bar', $bar = new \stdClass());
  96. $this->assertEquals($bar, $builder->get('bar'), '->get() returns the service associated with the id');
  97. $builder->register('bar', 'stdClass');
  98. $this->assertEquals($bar, $builder->get('bar'), '->get() returns the service associated with the id even if a definition has been defined');
  99. $builder->register('baz', 'stdClass')->setArguments(array(new Reference('baz')));
  100. try {
  101. @$builder->get('baz');
  102. $this->fail('->get() throws a ServiceCircularReferenceException if the service has a circular reference to itself');
  103. } catch (ServiceCircularReferenceException $e) {
  104. $this->assertEquals('Circular reference detected for service "baz", path: "baz".', $e->getMessage(), '->get() throws a LogicException if the service has a circular reference to itself');
  105. }
  106. $this->assertSame($builder->get('bar'), $builder->get('bar'), '->get() always returns the same instance if the service is shared');
  107. }
  108. public function testNonSharedServicesReturnsDifferentInstances()
  109. {
  110. $builder = new ContainerBuilder();
  111. $builder->register('bar', 'stdClass')->setShared(false);
  112. $this->assertNotSame($builder->get('bar'), $builder->get('bar'));
  113. }
  114. /**
  115. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  116. * @dataProvider provideBadId
  117. */
  118. public function testBadAliasId($id)
  119. {
  120. $builder = new ContainerBuilder();
  121. $builder->setAlias($id, 'foo');
  122. }
  123. /**
  124. * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  125. * @dataProvider provideBadId
  126. */
  127. public function testBadDefinitionId($id)
  128. {
  129. $builder = new ContainerBuilder();
  130. $builder->setDefinition($id, new Definition('Foo'));
  131. }
  132. public function provideBadId()
  133. {
  134. return [
  135. [''],
  136. ["\0"],
  137. ["\r"],
  138. ["\n"],
  139. ["'"],
  140. ['ab\\'],
  141. ];
  142. }
  143. /**
  144. * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException
  145. * @expectedExceptionMessage You have requested a synthetic service ("foo"). The DIC does not know how to construct this service.
  146. */
  147. public function testGetUnsetLoadingServiceWhenCreateServiceThrowsAnException()
  148. {
  149. $builder = new ContainerBuilder();
  150. $builder->register('foo', 'stdClass')->setSynthetic(true);
  151. // we expect a RuntimeException here as foo is synthetic
  152. try {
  153. $builder->get('foo');
  154. } catch (RuntimeException $e) {
  155. }
  156. // we must also have the same RuntimeException here
  157. $builder->get('foo');
  158. }
  159. /**
  160. * @group legacy
  161. */
  162. public function testGetReturnsNullOnInactiveScope()
  163. {
  164. $builder = new ContainerBuilder();
  165. $builder->register('foo', 'stdClass')->setScope('request');
  166. $this->assertNull($builder->get('foo', ContainerInterface::NULL_ON_INVALID_REFERENCE));
  167. }
  168. /**
  169. * @group legacy
  170. */
  171. public function testGetReturnsNullOnInactiveScopeWhenServiceIsCreatedByAMethod()
  172. {
  173. $builder = new ProjectContainer();
  174. $this->assertNull($builder->get('foobaz', ContainerInterface::NULL_ON_INVALID_REFERENCE));
  175. }
  176. public function testGetServiceIds()
  177. {
  178. $builder = new ContainerBuilder();
  179. $builder->register('foo', 'stdClass');
  180. $builder->bar = $bar = new \stdClass();
  181. $builder->register('bar', 'stdClass');
  182. $this->assertEquals(array('foo', 'bar', 'service_container'), $builder->getServiceIds(), '->getServiceIds() returns all defined service ids');
  183. }
  184. public function testAliases()
  185. {
  186. $builder = new ContainerBuilder();
  187. $builder->register('foo', 'stdClass');
  188. $builder->setAlias('bar', 'foo');
  189. $this->assertTrue($builder->hasAlias('bar'), '->hasAlias() returns true if the alias exists');
  190. $this->assertFalse($builder->hasAlias('foobar'), '->hasAlias() returns false if the alias does not exist');
  191. $this->assertEquals('foo', (string) $builder->getAlias('bar'), '->getAlias() returns the aliased service');
  192. $this->assertTrue($builder->has('bar'), '->setAlias() defines a new service');
  193. $this->assertSame($builder->get('bar'), $builder->get('foo'), '->setAlias() creates a service that is an alias to another one');
  194. try {
  195. $builder->setAlias('foobar', 'foobar');
  196. $this->fail('->setAlias() throws an InvalidArgumentException if the alias references itself');
  197. } catch (\InvalidArgumentException $e) {
  198. $this->assertEquals('An alias can not reference itself, got a circular reference on "foobar".', $e->getMessage(), '->setAlias() throws an InvalidArgumentException if the alias references itself');
  199. }
  200. try {
  201. $builder->getAlias('foobar');
  202. $this->fail('->getAlias() throws an InvalidArgumentException if the alias does not exist');
  203. } catch (\InvalidArgumentException $e) {
  204. $this->assertEquals('The service alias "foobar" does not exist.', $e->getMessage(), '->getAlias() throws an InvalidArgumentException if the alias does not exist');
  205. }
  206. }
  207. public function testGetAliases()
  208. {
  209. $builder = new ContainerBuilder();
  210. $builder->setAlias('bar', 'foo');
  211. $builder->setAlias('foobar', 'foo');
  212. $builder->setAlias('moo', new Alias('foo', false));
  213. $aliases = $builder->getAliases();
  214. $this->assertEquals('foo', (string) $aliases['bar']);
  215. $this->assertTrue($aliases['bar']->isPublic());
  216. $this->assertEquals('foo', (string) $aliases['foobar']);
  217. $this->assertEquals('foo', (string) $aliases['moo']);
  218. $this->assertFalse($aliases['moo']->isPublic());
  219. $builder->register('bar', 'stdClass');
  220. $this->assertFalse($builder->hasAlias('bar'));
  221. $builder->set('foobar', 'stdClass');
  222. $builder->set('moo', 'stdClass');
  223. $this->assertCount(0, $builder->getAliases(), '->getAliases() does not return aliased services that have been overridden');
  224. }
  225. public function testSetAliases()
  226. {
  227. $builder = new ContainerBuilder();
  228. $builder->setAliases(array('bar' => 'foo', 'foobar' => 'foo'));
  229. $aliases = $builder->getAliases();
  230. $this->assertArrayHasKey('bar', $aliases);
  231. $this->assertArrayHasKey('foobar', $aliases);
  232. }
  233. public function testAddAliases()
  234. {
  235. $builder = new ContainerBuilder();
  236. $builder->setAliases(array('bar' => 'foo'));
  237. $builder->addAliases(array('foobar' => 'foo'));
  238. $aliases = $builder->getAliases();
  239. $this->assertArrayHasKey('bar', $aliases);
  240. $this->assertArrayHasKey('foobar', $aliases);
  241. }
  242. public function testSetReplacesAlias()
  243. {
  244. $builder = new ContainerBuilder();
  245. $builder->setAlias('alias', 'aliased');
  246. $builder->set('aliased', new \stdClass());
  247. $builder->set('alias', $foo = new \stdClass());
  248. $this->assertSame($foo, $builder->get('alias'), '->set() replaces an existing alias');
  249. }
  250. public function testAliasesKeepInvalidBehavior()
  251. {
  252. $builder = new ContainerBuilder();
  253. $aliased = new Definition('stdClass');
  254. $aliased->addMethodCall('setBar', array(new Reference('bar', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)));
  255. $builder->setDefinition('aliased', $aliased);
  256. $builder->setAlias('alias', 'aliased');
  257. $this->assertEquals(new \stdClass(), $builder->get('alias'));
  258. }
  259. public function testAddGetCompilerPass()
  260. {
  261. $builder = new ContainerBuilder();
  262. $builder->setResourceTracking(false);
  263. $builderCompilerPasses = $builder->getCompiler()->getPassConfig()->getPasses();
  264. $builder->addCompilerPass($this->getMockBuilder('Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface')->getMock());
  265. $this->assertCount(\count($builder->getCompiler()->getPassConfig()->getPasses()) - 1, $builderCompilerPasses);
  266. }
  267. public function testCreateService()
  268. {
  269. $builder = new ContainerBuilder();
  270. $builder->register('foo1', 'Bar\FooClass')->setFile(__DIR__.'/Fixtures/includes/foo.php');
  271. $this->assertInstanceOf('\Bar\FooClass', $builder->get('foo1'), '->createService() requires the file defined by the service definition');
  272. $builder->register('foo2', 'Bar\FooClass')->setFile(__DIR__.'/Fixtures/includes/%file%.php');
  273. $builder->setParameter('file', 'foo');
  274. $this->assertInstanceOf('\Bar\FooClass', $builder->get('foo2'), '->createService() replaces parameters in the file provided by the service definition');
  275. }
  276. public function testCreateProxyWithRealServiceInstantiator()
  277. {
  278. $builder = new ContainerBuilder();
  279. $builder->register('foo1', 'Bar\FooClass')->setFile(__DIR__.'/Fixtures/includes/foo.php');
  280. $builder->getDefinition('foo1')->setLazy(true);
  281. $foo1 = $builder->get('foo1');
  282. $this->assertSame($foo1, $builder->get('foo1'), 'The same proxy is retrieved on multiple subsequent calls');
  283. $this->assertSame('Bar\FooClass', \get_class($foo1));
  284. }
  285. public function testCreateServiceClass()
  286. {
  287. $builder = new ContainerBuilder();
  288. $builder->register('foo1', '%class%');
  289. $builder->setParameter('class', 'stdClass');
  290. $this->assertInstanceOf('\stdClass', $builder->get('foo1'), '->createService() replaces parameters in the class provided by the service definition');
  291. }
  292. public function testCreateServiceArguments()
  293. {
  294. $builder = new ContainerBuilder();
  295. $builder->register('bar', 'stdClass');
  296. $builder->register('foo1', 'Bar\FooClass')->addArgument(array('foo' => '%value%', '%value%' => 'foo', new Reference('bar'), '%%unescape_it%%'));
  297. $builder->setParameter('value', 'bar');
  298. $this->assertEquals(array('foo' => 'bar', 'bar' => 'foo', $builder->get('bar'), '%unescape_it%'), $builder->get('foo1')->arguments, '->createService() replaces parameters and service references in the arguments provided by the service definition');
  299. }
  300. public function testCreateServiceFactory()
  301. {
  302. $builder = new ContainerBuilder();
  303. $builder->register('foo', 'Bar\FooClass')->setFactory('Bar\FooClass::getInstance');
  304. $builder->register('qux', 'Bar\FooClass')->setFactory(array('Bar\FooClass', 'getInstance'));
  305. $builder->register('bar', 'Bar\FooClass')->setFactory(array(new Definition('Bar\FooClass'), 'getInstance'));
  306. $builder->register('baz', 'Bar\FooClass')->setFactory(array(new Reference('bar'), 'getInstance'));
  307. $this->assertTrue($builder->get('foo')->called, '->createService() calls the factory method to create the service instance');
  308. $this->assertTrue($builder->get('qux')->called, '->createService() calls the factory method to create the service instance');
  309. $this->assertTrue($builder->get('bar')->called, '->createService() uses anonymous service as factory');
  310. $this->assertTrue($builder->get('baz')->called, '->createService() uses another service as factory');
  311. }
  312. /**
  313. * @group legacy
  314. */
  315. public function testLegacyCreateServiceFactory()
  316. {
  317. $builder = new ContainerBuilder();
  318. $builder->register('bar', 'Bar\FooClass');
  319. $builder
  320. ->register('foo1', 'Bar\FooClass')
  321. ->setFactoryClass('%foo_class%')
  322. ->setFactoryMethod('getInstance')
  323. ->addArgument(array('foo' => '%value%', '%value%' => 'foo', new Reference('bar')))
  324. ;
  325. $builder->setParameter('value', 'bar');
  326. $builder->setParameter('foo_class', 'Bar\FooClass');
  327. $this->assertTrue($builder->get('foo1')->called, '->createService() calls the factory method to create the service instance');
  328. $this->assertEquals(array('foo' => 'bar', 'bar' => 'foo', $builder->get('bar')), $builder->get('foo1')->arguments, '->createService() passes the arguments to the factory method');
  329. }
  330. /**
  331. * @group legacy
  332. */
  333. public function testLegacyCreateServiceFactoryService()
  334. {
  335. $builder = new ContainerBuilder();
  336. $builder->register('foo_service', 'Bar\FooClass');
  337. $builder
  338. ->register('foo', 'Bar\FooClass')
  339. ->setFactoryService('%foo_service%')
  340. ->setFactoryMethod('getInstance')
  341. ;
  342. $builder->setParameter('foo_service', 'foo_service');
  343. $this->assertTrue($builder->get('foo')->called, '->createService() calls the factory method to create the service instance');
  344. }
  345. public function testCreateServiceMethodCalls()
  346. {
  347. $builder = new ContainerBuilder();
  348. $builder->register('bar', 'stdClass');
  349. $builder->register('foo1', 'Bar\FooClass')->addMethodCall('setBar', array(array('%value%', new Reference('bar'))));
  350. $builder->setParameter('value', 'bar');
  351. $this->assertEquals(array('bar', $builder->get('bar')), $builder->get('foo1')->bar, '->createService() replaces the values in the method calls arguments');
  352. }
  353. public function testCreateServiceMethodCallsWithEscapedParam()
  354. {
  355. $builder = new ContainerBuilder();
  356. $builder->register('bar', 'stdClass');
  357. $builder->register('foo1', 'Bar\FooClass')->addMethodCall('setBar', array(array('%%unescape_it%%')));
  358. $builder->setParameter('value', 'bar');
  359. $this->assertEquals(array('%unescape_it%'), $builder->get('foo1')->bar, '->createService() replaces the values in the method calls arguments');
  360. }
  361. public function testCreateServiceProperties()
  362. {
  363. $builder = new ContainerBuilder();
  364. $builder->register('bar', 'stdClass');
  365. $builder->register('foo1', 'Bar\FooClass')->setProperty('bar', array('%value%', new Reference('bar'), '%%unescape_it%%'));
  366. $builder->setParameter('value', 'bar');
  367. $this->assertEquals(array('bar', $builder->get('bar'), '%unescape_it%'), $builder->get('foo1')->bar, '->createService() replaces the values in the properties');
  368. }
  369. public function testCreateServiceConfigurator()
  370. {
  371. $builder = new ContainerBuilder();
  372. $builder->register('foo1', 'Bar\FooClass')->setConfigurator('sc_configure');
  373. $this->assertTrue($builder->get('foo1')->configured, '->createService() calls the configurator');
  374. $builder->register('foo2', 'Bar\FooClass')->setConfigurator(array('%class%', 'configureStatic'));
  375. $builder->setParameter('class', 'BazClass');
  376. $this->assertTrue($builder->get('foo2')->configured, '->createService() calls the configurator');
  377. $builder->register('baz', 'BazClass');
  378. $builder->register('foo3', 'Bar\FooClass')->setConfigurator(array(new Reference('baz'), 'configure'));
  379. $this->assertTrue($builder->get('foo3')->configured, '->createService() calls the configurator');
  380. $builder->register('foo4', 'Bar\FooClass')->setConfigurator(array($builder->getDefinition('baz'), 'configure'));
  381. $this->assertTrue($builder->get('foo4')->configured, '->createService() calls the configurator');
  382. $builder->register('foo5', 'Bar\FooClass')->setConfigurator('foo');
  383. try {
  384. $builder->get('foo5');
  385. $this->fail('->createService() throws an InvalidArgumentException if the configure callable is not a valid callable');
  386. } catch (\InvalidArgumentException $e) {
  387. $this->assertEquals('The configure callable for class "Bar\FooClass" is not a callable.', $e->getMessage(), '->createService() throws an InvalidArgumentException if the configure callable is not a valid callable');
  388. }
  389. }
  390. /**
  391. * @expectedException \RuntimeException
  392. */
  393. public function testCreateSyntheticService()
  394. {
  395. $builder = new ContainerBuilder();
  396. $builder->register('foo', 'Bar\FooClass')->setSynthetic(true);
  397. $builder->get('foo');
  398. }
  399. public function testCreateServiceWithExpression()
  400. {
  401. $builder = new ContainerBuilder();
  402. $builder->setParameter('bar', 'bar');
  403. $builder->register('bar', 'BarClass');
  404. $builder->register('foo', 'Bar\FooClass')->addArgument(array('foo' => new Expression('service("bar").foo ~ parameter("bar")')));
  405. $this->assertEquals('foobar', $builder->get('foo')->arguments['foo']);
  406. }
  407. public function testResolveServices()
  408. {
  409. $builder = new ContainerBuilder();
  410. $builder->register('foo', 'Bar\FooClass');
  411. $this->assertEquals($builder->get('foo'), $builder->resolveServices(new Reference('foo')), '->resolveServices() resolves service references to service instances');
  412. $this->assertEquals(array('foo' => array('foo', $builder->get('foo'))), $builder->resolveServices(array('foo' => array('foo', new Reference('foo')))), '->resolveServices() resolves service references to service instances in nested arrays');
  413. $this->assertEquals($builder->get('foo'), $builder->resolveServices(new Expression('service("foo")')), '->resolveServices() resolves expressions');
  414. }
  415. /**
  416. * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException
  417. * @expectedExceptionMessage Constructing service "foo" from a parent definition is not supported at build time.
  418. */
  419. public function testResolveServicesWithDecoratedDefinition()
  420. {
  421. $builder = new ContainerBuilder();
  422. $builder->setDefinition('grandpa', new Definition('stdClass'));
  423. $builder->setDefinition('parent', new DefinitionDecorator('grandpa'));
  424. $builder->setDefinition('foo', new DefinitionDecorator('parent'));
  425. $builder->get('foo');
  426. }
  427. public function testResolveServicesWithCustomDefinitionClass()
  428. {
  429. $builder = new ContainerBuilder();
  430. $builder->setDefinition('foo', new CustomDefinition('stdClass'));
  431. $this->assertInstanceOf('stdClass', $builder->get('foo'));
  432. }
  433. public function testMerge()
  434. {
  435. $container = new ContainerBuilder(new ParameterBag(array('bar' => 'foo')));
  436. $container->setResourceTracking(false);
  437. $config = new ContainerBuilder(new ParameterBag(array('foo' => 'bar')));
  438. $container->merge($config);
  439. $this->assertEquals(array('bar' => 'foo', 'foo' => 'bar'), $container->getParameterBag()->all(), '->merge() merges current parameters with the loaded ones');
  440. $container = new ContainerBuilder(new ParameterBag(array('bar' => 'foo')));
  441. $container->setResourceTracking(false);
  442. $config = new ContainerBuilder(new ParameterBag(array('foo' => '%bar%')));
  443. $container->merge($config);
  444. $container->compile();
  445. $this->assertEquals(array('bar' => 'foo', 'foo' => 'foo'), $container->getParameterBag()->all(), '->merge() evaluates the values of the parameters towards already defined ones');
  446. $container = new ContainerBuilder(new ParameterBag(array('bar' => 'foo')));
  447. $container->setResourceTracking(false);
  448. $config = new ContainerBuilder(new ParameterBag(array('foo' => '%bar%', 'baz' => '%foo%')));
  449. $container->merge($config);
  450. $container->compile();
  451. $this->assertEquals(array('bar' => 'foo', 'foo' => 'foo', 'baz' => 'foo'), $container->getParameterBag()->all(), '->merge() evaluates the values of the parameters towards already defined ones');
  452. $container = new ContainerBuilder();
  453. $container->setResourceTracking(false);
  454. $container->register('foo', 'Bar\FooClass');
  455. $container->register('bar', 'BarClass');
  456. $config = new ContainerBuilder();
  457. $config->setDefinition('baz', new Definition('BazClass'));
  458. $config->setAlias('alias_for_foo', 'foo');
  459. $container->merge($config);
  460. $this->assertEquals(array('foo', 'bar', 'baz'), array_keys($container->getDefinitions()), '->merge() merges definitions already defined ones');
  461. $aliases = $container->getAliases();
  462. $this->assertArrayHasKey('alias_for_foo', $aliases);
  463. $this->assertEquals('foo', (string) $aliases['alias_for_foo']);
  464. $container = new ContainerBuilder();
  465. $container->setResourceTracking(false);
  466. $container->register('foo', 'Bar\FooClass');
  467. $config->setDefinition('foo', new Definition('BazClass'));
  468. $container->merge($config);
  469. $this->assertEquals('BazClass', $container->getDefinition('foo')->getClass(), '->merge() overrides already defined services');
  470. }
  471. /**
  472. * @expectedException \LogicException
  473. */
  474. public function testMergeLogicException()
  475. {
  476. $container = new ContainerBuilder();
  477. $container->setResourceTracking(false);
  478. $container->compile();
  479. $container->merge(new ContainerBuilder());
  480. }
  481. public function testfindTaggedServiceIds()
  482. {
  483. $builder = new ContainerBuilder();
  484. $builder
  485. ->register('foo', 'Bar\FooClass')
  486. ->addTag('foo', array('foo' => 'foo'))
  487. ->addTag('bar', array('bar' => 'bar'))
  488. ->addTag('foo', array('foofoo' => 'foofoo'))
  489. ;
  490. $this->assertEquals($builder->findTaggedServiceIds('foo'), array(
  491. 'foo' => array(
  492. array('foo' => 'foo'),
  493. array('foofoo' => 'foofoo'),
  494. ),
  495. ), '->findTaggedServiceIds() returns an array of service ids and its tag attributes');
  496. $this->assertEquals(array(), $builder->findTaggedServiceIds('foobar'), '->findTaggedServiceIds() returns an empty array if there is annotated services');
  497. }
  498. public function testFindUnusedTags()
  499. {
  500. $builder = new ContainerBuilder();
  501. $builder
  502. ->register('foo', 'Bar\FooClass')
  503. ->addTag('kernel.event_listener', array('foo' => 'foo'))
  504. ->addTag('kenrel.event_listener', array('bar' => 'bar'))
  505. ;
  506. $builder->findTaggedServiceIds('kernel.event_listener');
  507. $this->assertEquals(array('kenrel.event_listener'), $builder->findUnusedTags(), '->findUnusedTags() returns an array with unused tags');
  508. }
  509. public function testFindDefinition()
  510. {
  511. $container = new ContainerBuilder();
  512. $container->setDefinition('foo', $definition = new Definition('Bar\FooClass'));
  513. $container->setAlias('bar', 'foo');
  514. $container->setAlias('foobar', 'bar');
  515. $this->assertEquals($definition, $container->findDefinition('foobar'), '->findDefinition() returns a Definition');
  516. }
  517. public function testAddObjectResource()
  518. {
  519. $container = new ContainerBuilder();
  520. $container->setResourceTracking(false);
  521. $container->addObjectResource(new \BarClass());
  522. $this->assertEmpty($container->getResources(), 'No resources get registered without resource tracking');
  523. $container->setResourceTracking(true);
  524. $container->addObjectResource(new \BarClass());
  525. $resources = $container->getResources();
  526. $this->assertCount(1, $resources, '1 resource was registered');
  527. /* @var $resource \Symfony\Component\Config\Resource\FileResource */
  528. $resource = end($resources);
  529. $this->assertInstanceOf('Symfony\Component\Config\Resource\FileResource', $resource);
  530. $this->assertSame(realpath(__DIR__.'/Fixtures/includes/classes.php'), realpath($resource->getResource()));
  531. }
  532. public function testAddClassResource()
  533. {
  534. $container = new ContainerBuilder();
  535. $container->setResourceTracking(false);
  536. $container->addClassResource(new \ReflectionClass('BarClass'));
  537. $this->assertEmpty($container->getResources(), 'No resources get registered without resource tracking');
  538. $container->setResourceTracking(true);
  539. $container->addClassResource(new \ReflectionClass('BarClass'));
  540. $resources = $container->getResources();
  541. $this->assertCount(1, $resources, '1 resource was registered');
  542. /* @var $resource \Symfony\Component\Config\Resource\FileResource */
  543. $resource = end($resources);
  544. $this->assertInstanceOf('Symfony\Component\Config\Resource\FileResource', $resource);
  545. $this->assertSame(realpath(__DIR__.'/Fixtures/includes/classes.php'), realpath($resource->getResource()));
  546. }
  547. public function testCompilesClassDefinitionsOfLazyServices()
  548. {
  549. $container = new ContainerBuilder();
  550. $this->assertEmpty($container->getResources(), 'No resources get registered without resource tracking');
  551. $container->register('foo', 'BarClass');
  552. $container->getDefinition('foo')->setLazy(true);
  553. $container->compile();
  554. $classesPath = realpath(__DIR__.'/Fixtures/includes/classes.php');
  555. $matchingResources = array_filter(
  556. $container->getResources(),
  557. function (ResourceInterface $resource) use ($classesPath) {
  558. return $resource instanceof FileResource && $classesPath === realpath($resource->getResource());
  559. }
  560. );
  561. $this->assertNotEmpty($matchingResources);
  562. }
  563. public function testResources()
  564. {
  565. $container = new ContainerBuilder();
  566. $container->addResource($a = new FileResource(__DIR__.'/Fixtures/xml/services1.xml'));
  567. $container->addResource($b = new FileResource(__DIR__.'/Fixtures/xml/services2.xml'));
  568. $resources = array();
  569. foreach ($container->getResources() as $resource) {
  570. if (false === strpos($resource, '.php')) {
  571. $resources[] = $resource;
  572. }
  573. }
  574. $this->assertEquals(array($a, $b), $resources, '->getResources() returns an array of resources read for the current configuration');
  575. $this->assertSame($container, $container->setResources(array()));
  576. $this->assertEquals(array(), $container->getResources());
  577. }
  578. public function testExtension()
  579. {
  580. $container = new ContainerBuilder();
  581. $container->setResourceTracking(false);
  582. $container->registerExtension($extension = new \ProjectExtension());
  583. $this->assertSame($container->getExtension('project'), $extension, '->registerExtension() registers an extension');
  584. $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('LogicException');
  585. $container->getExtension('no_registered');
  586. }
  587. public function testRegisteredButNotLoadedExtension()
  588. {
  589. $extension = $this->getMockBuilder('Symfony\\Component\\DependencyInjection\\Extension\\ExtensionInterface')->getMock();
  590. $extension->expects($this->once())->method('getAlias')->will($this->returnValue('project'));
  591. $extension->expects($this->never())->method('load');
  592. $container = new ContainerBuilder();
  593. $container->setResourceTracking(false);
  594. $container->registerExtension($extension);
  595. $container->compile();
  596. }
  597. public function testRegisteredAndLoadedExtension()
  598. {
  599. $extension = $this->getMockBuilder('Symfony\\Component\\DependencyInjection\\Extension\\ExtensionInterface')->getMock();
  600. $extension->expects($this->exactly(2))->method('getAlias')->will($this->returnValue('project'));
  601. $extension->expects($this->once())->method('load')->with(array(array('foo' => 'bar')));
  602. $container = new ContainerBuilder();
  603. $container->setResourceTracking(false);
  604. $container->registerExtension($extension);
  605. $container->loadFromExtension('project', array('foo' => 'bar'));
  606. $container->compile();
  607. }
  608. public function testPrivateServiceUser()
  609. {
  610. $fooDefinition = new Definition('BarClass');
  611. $fooUserDefinition = new Definition('BarUserClass', array(new Reference('bar')));
  612. $container = new ContainerBuilder();
  613. $container->setResourceTracking(false);
  614. $fooDefinition->setPublic(false);
  615. $container->addDefinitions(array(
  616. 'bar' => $fooDefinition,
  617. 'bar_user' => $fooUserDefinition,
  618. ));
  619. $container->compile();
  620. $this->assertInstanceOf('BarClass', $container->get('bar_user')->bar);
  621. }
  622. /**
  623. * @expectedException \BadMethodCallException
  624. */
  625. public function testThrowsExceptionWhenSetServiceOnAFrozenContainer()
  626. {
  627. $container = new ContainerBuilder();
  628. $container->setResourceTracking(false);
  629. $container->setDefinition('a', new Definition('stdClass'));
  630. $container->compile();
  631. $container->set('a', new \stdClass());
  632. }
  633. public function testThrowsExceptionWhenAddServiceOnAFrozenContainer()
  634. {
  635. $container = new ContainerBuilder();
  636. $container->compile();
  637. $container->set('a', $foo = new \stdClass());
  638. $this->assertSame($foo, $container->get('a'));
  639. }
  640. public function testNoExceptionWhenSetSyntheticServiceOnAFrozenContainer()
  641. {
  642. $container = new ContainerBuilder();
  643. $def = new Definition('stdClass');
  644. $def->setSynthetic(true);
  645. $container->setDefinition('a', $def);
  646. $container->compile();
  647. $container->set('a', $a = new \stdClass());
  648. $this->assertEquals($a, $container->get('a'));
  649. }
  650. /**
  651. * @group legacy
  652. */
  653. public function testLegacySetOnSynchronizedService()
  654. {
  655. $container = new ContainerBuilder();
  656. $container->register('baz', 'BazClass')
  657. ->setSynchronized(true)
  658. ;
  659. $container->register('bar', 'BarClass')
  660. ->addMethodCall('setBaz', array(new Reference('baz')))
  661. ;
  662. $container->set('baz', $baz = new \BazClass());
  663. $this->assertSame($baz, $container->get('bar')->getBaz());
  664. $container->set('baz', $baz = new \BazClass());
  665. $this->assertSame($baz, $container->get('bar')->getBaz());
  666. }
  667. /**
  668. * @group legacy
  669. */
  670. public function testLegacySynchronizedServiceWithScopes()
  671. {
  672. $container = new ContainerBuilder();
  673. $container->addScope(new Scope('foo'));
  674. $container->register('baz', 'BazClass')
  675. ->setSynthetic(true)
  676. ->setSynchronized(true)
  677. ->setScope('foo')
  678. ;
  679. $container->register('bar', 'BarClass')
  680. ->addMethodCall('setBaz', array(new Reference('baz', ContainerInterface::NULL_ON_INVALID_REFERENCE, false)))
  681. ;
  682. $container->compile();
  683. $container->enterScope('foo');
  684. $container->set('baz', $outerBaz = new \BazClass(), 'foo');
  685. $this->assertSame($outerBaz, $container->get('bar')->getBaz());
  686. $container->enterScope('foo');
  687. $container->set('baz', $innerBaz = new \BazClass(), 'foo');
  688. $this->assertSame($innerBaz, $container->get('bar')->getBaz());
  689. $container->leaveScope('foo');
  690. $this->assertNotSame($innerBaz, $container->get('bar')->getBaz());
  691. $this->assertSame($outerBaz, $container->get('bar')->getBaz());
  692. $container->leaveScope('foo');
  693. }
  694. /**
  695. * @expectedException \BadMethodCallException
  696. */
  697. public function testThrowsExceptionWhenSetDefinitionOnAFrozenContainer()
  698. {
  699. $container = new ContainerBuilder();
  700. $container->setResourceTracking(false);
  701. $container->compile();
  702. $container->setDefinition('a', new Definition());
  703. }
  704. public function testExtensionConfig()
  705. {
  706. $container = new ContainerBuilder();
  707. $configs = $container->getExtensionConfig('foo');
  708. $this->assertEmpty($configs);
  709. $first = array('foo' => 'bar');
  710. $container->prependExtensionConfig('foo', $first);
  711. $configs = $container->getExtensionConfig('foo');
  712. $this->assertEquals(array($first), $configs);
  713. $second = array('ding' => 'dong');
  714. $container->prependExtensionConfig('foo', $second);
  715. $configs = $container->getExtensionConfig('foo');
  716. $this->assertEquals(array($second, $first), $configs);
  717. }
  718. public function testAbstractAlias()
  719. {
  720. $container = new ContainerBuilder();
  721. $abstract = new Definition('AbstractClass');
  722. $abstract->setAbstract(true);
  723. $container->setDefinition('abstract_service', $abstract);
  724. $container->setAlias('abstract_alias', 'abstract_service');
  725. $container->compile();
  726. $this->assertSame('abstract_service', (string) $container->getAlias('abstract_alias'));
  727. }
  728. public function testLazyLoadedService()
  729. {
  730. $loader = new ClosureLoader($container = new ContainerBuilder());
  731. $loader->load(function (ContainerBuilder $container) {
  732. $container->set('a', new \BazClass());
  733. $definition = new Definition('BazClass');
  734. $definition->setLazy(true);
  735. $container->setDefinition('a', $definition);
  736. });
  737. $container->setResourceTracking(true);
  738. $container->compile();
  739. $class = new \BazClass();
  740. $reflectionClass = new \ReflectionClass($class);
  741. $r = new \ReflectionProperty($container, 'resources');
  742. $r->setAccessible(true);
  743. $resources = $r->getValue($container);
  744. $classInList = false;
  745. foreach ($resources as $resource) {
  746. if ($resource->getResource() === $reflectionClass->getFileName()) {
  747. $classInList = true;
  748. break;
  749. }
  750. }
  751. $this->assertTrue($classInList);
  752. }
  753. public function testInlinedDefinitions()
  754. {
  755. $container = new ContainerBuilder();
  756. $definition = new Definition('BarClass');
  757. $container->register('bar_user', 'BarUserClass')
  758. ->addArgument($definition)
  759. ->setProperty('foo', $definition);
  760. $container->register('bar', 'BarClass')
  761. ->setProperty('foo', $definition)
  762. ->addMethodCall('setBaz', array($definition));
  763. $barUser = $container->get('bar_user');
  764. $bar = $container->get('bar');
  765. $this->assertSame($barUser->foo, $barUser->bar);
  766. $this->assertSame($bar->foo, $bar->getBaz());
  767. $this->assertNotSame($bar->foo, $barUser->foo);
  768. }
  769. public function testInitializePropertiesBeforeMethodCalls()
  770. {
  771. $container = new ContainerBuilder();
  772. $container->register('foo', 'stdClass');
  773. $container->register('bar', 'MethodCallClass')
  774. ->setProperty('simple', 'bar')
  775. ->setProperty('complex', new Reference('foo'))
  776. ->addMethodCall('callMe');
  777. $container->compile();
  778. $this->assertTrue($container->get('bar')->callPassed(), '->compile() initializes properties before method calls');
  779. }
  780. public function testAutowiring()
  781. {
  782. $container = new ContainerBuilder();
  783. $container->register('a', __NAMESPACE__.'\A');
  784. $bDefinition = $container->register('b', __NAMESPACE__.'\B');
  785. $bDefinition->setAutowired(true);
  786. $container->compile();
  787. $this->assertEquals('a', (string) $container->getDefinition('b')->getArgument(0));
  788. }
  789. /**
  790. * This test checks the trigger of a deprecation note and should not be removed in major releases.
  791. *
  792. * @group legacy
  793. * @expectedDeprecation The "foo" service is deprecated. You should stop using it, as it will soon be removed.
  794. */
  795. public function testPrivateServiceTriggersDeprecation()
  796. {
  797. $container = new ContainerBuilder();
  798. $container->register('foo', 'stdClass')
  799. ->setPublic(false)
  800. ->setDeprecated(true);
  801. $container->register('bar', 'stdClass')
  802. ->setPublic(true)
  803. ->setProperty('foo', new Reference('foo'));
  804. $container->compile();
  805. $container->get('bar');
  806. }
  807. }
  808. class FooClass
  809. {
  810. }
  811. class ProjectContainer extends ContainerBuilder
  812. {
  813. public function getFoobazService()
  814. {
  815. throw new InactiveScopeException('foo', 'request');
  816. }
  817. }
  818. class A
  819. {
  820. }
  821. class B
  822. {
  823. public function __construct(A $a)
  824. {
  825. }
  826. }