Skip to content

Commit bccb074

Browse files
Evan Shawnicolas-grekas
authored andcommitted
[Contracts] Fix setting $container before calling parent::setContainer in ServiceSubscriberTrait
1 parent 29f46fc commit bccb074

File tree

2 files changed

+36
-4
lines changed

2 files changed

+36
-4
lines changed

src/Symfony/Contracts/Service/ServiceSubscriberTrait.php

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -98,12 +98,13 @@ public static function getSubscribedServices(): array
9898
*/
9999
public function setContainer(ContainerInterface $container)
100100
{
101-
$this->container = $container;
102-
101+
$ret = null;
103102
if (method_exists(get_parent_class(self::class) ?: '', __FUNCTION__)) {
104-
return parent::setContainer($container);
103+
$ret = parent::setContainer($container);
105104
}
106105

107-
return null;
106+
$this->container = $container;
107+
108+
return $ret;
108109
}
109110
}

src/Symfony/Contracts/Tests/Service/ServiceSubscriberTraitTest.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,18 @@ public function testParentNotCalledIfNoParent()
8181
$this->assertSame([], $service::getSubscribedServices());
8282
}
8383

84+
public function testSetContainerCalledFirstOnParent()
85+
{
86+
$container1 = new class([]) implements ContainerInterface {
87+
use ServiceLocatorTrait;
88+
};
89+
$container2 = clone $container1;
90+
91+
$testService = new TestService2();
92+
$this->assertNull($testService->setContainer($container1));
93+
$this->assertSame($container1, $testService->setContainer($container2));
94+
}
95+
8496
/**
8597
* @requires PHP 8
8698
*
@@ -161,3 +173,22 @@ public static function __callStatic($method, $args)
161173
class Service3
162174
{
163175
}
176+
177+
class ParentTestService2
178+
{
179+
/** @var ContainerInterface */
180+
protected $container;
181+
182+
public function setContainer(ContainerInterface $container)
183+
{
184+
$previous = $this->container;
185+
$this->container = $container;
186+
187+
return $previous;
188+
}
189+
}
190+
191+
class TestService2 extends ParentTestService2 implements ServiceSubscriberInterface
192+
{
193+
use ServiceSubscriberTrait;
194+
}

0 commit comments

Comments
 (0)