bug #17742 [DependencyInjection] Fix #16461 Container::set() replace aliases (mnapoli)

This PR was submitted for the master branch but it was merged into the 2.3 branch instead (closes #17742).

Discussion
----------

[DependencyInjection] Fix #16461 Container::set() replace aliases

| Q             | A
| ------------- | ---
| Bug fix?      | yes
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | #16461
| License       | MIT
| Doc PR        | -

`Container::set()` now overrides any previously alias defined with the same name. Please see #16461 for the background.

Example:

- given `event_dispatcher` is an alias to `debug.event_dispatcher`
- when I run: `$container->set('event_dispatcher', new FakeEventDispatcher)`
- *before this patch*: nothing happens
- *after this patch*: the `event_dispatcher` is now my fake event dispatcher

Commits
-------

be85d16 [DependencyInjection] Fix #16461 Let Container::set() replace existing aliases
This commit is contained in:
Fabien Potencier 2016-02-12 09:48:06 +01:00
commit 2799b1cf04
3 changed files with 22 additions and 0 deletions

View File

@ -200,6 +200,10 @@ class Container implements IntrospectableContainerInterface
$this->scopedServices[$scope][$id] = $service;
}
if (isset($this->aliases[$id])) {
unset($this->aliases[$id]);
}
$this->services[$id] = $service;
if (method_exists($this, $method = 'synchronize'.strtr($id, $this->underscoreMap).'Service')) {

View File

@ -217,6 +217,16 @@ class ContainerBuilderTest extends \PHPUnit_Framework_TestCase
$this->assertTrue(isset($aliases['foobar']));
}
public function testSetReplacesAlias()
{
$builder = new ContainerBuilder();
$builder->setAlias('alias', 'aliased');
$builder->set('aliased', new \stdClass());
$builder->set('alias', $foo = new \stdClass());
$this->assertSame($foo, $builder->get('alias'), '->set() replaces an existing alias');
}
public function testAddGetCompilerPass()
{
$builder = new ContainerBuilder();

View File

@ -152,6 +152,14 @@ class ContainerTest extends \PHPUnit_Framework_TestCase
$this->assertSame($foo, $services['foo']['foo']);
}
public function testSetReplacesAlias()
{
$c = new ProjectServiceContainer();
$c->set('alias', $foo = new \stdClass());
$this->assertSame($foo, $c->get('alias'), '->set() replaces an existing alias');
}
public function testGet()
{
$sc = new ProjectServiceContainer();