Skip to content

Commit 1c2ab9d

Browse files
author
Evan Shaw
committed
Fix ServiceSubscriberTrait usage with AbstractController
The parent class's setContainer method should be called first, so that if the parent method relies on the old container, it will still work correctly.
1 parent 29f46fc commit 1c2ab9d

File tree

2 files changed

+35
-4
lines changed

2 files changed

+35
-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: 30 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,21 @@ 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+
return $previous;
187+
}
188+
}
189+
190+
class TestService2 extends ParentTestService2 implements ServiceSubscriberInterface
191+
{
192+
use ServiceSubscriberTrait;
193+
}

0 commit comments

Comments
 (0)