8000 [DependencyInjection] [POC] allow `ServiceSubscriberTrait` to autowire properties by kbond · Pull Request #46617 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[DependencyInjection] [POC] allow ServiceSubscriberTrait to autowire properties #46617

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,8 @@ public function testServiceSubscriberTraitWithSubscribedServiceAttribute()
TestServiceSubscriberChild::class.'::testDefinition4' => new ServiceClosureArgument(new TypedReference(TestDefinition3::class, TestDefinition3::class)),
TestServiceSubscriberParent::class.'::testDefinition1' => new ServiceClosureArgument(new TypedReference(TestDefinition1::class, TestDefinition1::class)),
'custom_name' => new ServiceClosureArgument(new TypedReference(TestDefinition3::class, TestDefinition3::class, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, 'custom_name')),
'testDefinition1' => new ServiceClosureArgument(new TypedReference(TestDefinition1::class, TestDefinition1::class, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, 'testDefinition1')),
'testDefinition2' => new ServiceClosureArgument(new TypedReference(TestDefinition2::class, TestDefinition2::class, ContainerInterface::IGNORE_ON_INVALID_REFERENCE, 'testDefinition2')),
];

$this->assertEquals($expected, $container->getDefinition((string) $locator->getFactory()[0])->getArgument(0));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ class TestServiceSubscriberChild extends TestServiceSubscriberParent
use ServiceSubscriberTrait;
use TestServiceSubscriberTrait;

#[SubscribedService]
private TestDefinition1 $testDefinition1;

#[SubscribedService]
private ?TestDefinition2 $testDefinition2;

#[SubscribedService]
private function testDefinition2(): ?TestDefinition2
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
*
* @author Kevin Bond <kevinbond@gmail.com>
*/
#[\Attribute(\Attribute::TARGET_METHOD)]
#[\Attribute(\Attribute::TARGET_METHOD | \Attribute::TARGET_PROPERTY)]
final class SubscribedService
{
/** @var object[] */
Expand Down
58 changes: 56 additions & 2 deletions src/Symfony/Contracts/Service/ServiceSubscriberTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@

/**
* Implementation of ServiceSubscriberInterface that determines subscribed services from
* method return types. Service ids are available as "ClassName::methodName".
* method return types and property type-hints for methods/properties marked with the
* "SubscribedService" attribute. Service ids are available as "ClassName::methodName"
* for methods and "propertyName" for properties.
*
* @author Kevin Bond <kevinbond@gmail.com>
*/
Expand All @@ -29,8 +31,39 @@ trait ServiceSubscriberTrait
public static function getSubscribedServices(): array
{
$services = method_exists(get_parent_class(self::class) ?: '', __FUNCTION__) ? parent::getSubscribedServices() : [];
$refClass = new \ReflectionClass(self::class);

foreach ((new \ReflectionClass(self::class))->getMethods() as $method) {
foreach ($refClass->getProperties() as $property) {
if (self::class !== $property->getDeclaringClass()->name) {
continue;
}

if (!$attribute = $property->getAttributes(SubscribedService::class)[0] ?? null) {
continue;
}

if ($property->isStatic()) {
throw new \LogicException(sprintf('Cannot use "%s" on property "%s::$%s" (can only be used on non-static properties with a type).', SubscribedService::class, self::class, $property->name));
}

if (!$type = $property->getType()) {
throw new \LogicException(sprintf('Cannot use "%s" on properties without a type in "%s::%s()".', SubscribedService::class, $property->name, self::class));
}

/* @var SubscribedService $attribute */
$attribute = $attribute->newInstance();
$attribute->key ??= $property->name;
$attribute->type ??= $type instanceof \ReflectionNamedType ? $type->getName() : (string) $type;
$attribute->nullable = $type->allowsNull();

if ($attribute->attributes) {
$services[] = $attribute;
} else {
$services[$attribute->key] = ($attribute->nullable ? '?' : '').$attribute->type;
}
}

foreach ($refClass->getMethods() as $method) {
if (self::class !== $method->getDeclaringClass()->name) {
continue;
}
Expand Down Expand Up @@ -68,10 +101,31 @@ public function setContainer(ContainerInterface $container): ?ContainerInterface
{
$this->container = $container;

foreach ((new \ReflectionClass(self::class))->getProperties() as $property) {
if (self::class !== $property->getDeclaringClass()->name) {
continue;
}

if (!$property->getAttributes(SubscribedService::class)) {
continue;
}

unset($this->{$property->name});
}

if (method_exists(get_parent_class(self::class) ?: '', __FUNCTION__)) {
return parent::setContainer($container);
}

return null;
}

public function __get(string $name): mixed
{
// TODO: ensure cannot be called from outside of the scope of the object?
// TODO: what if class has a child/parent that allows this?
// TODO: call parent::__get()?
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LazyGhostObjectTrait to the rescue somehow?

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not very familiar with this trait. How could it be used?


return $this->$name = $this->container->has($name) ? $this->container->get($name) : null;
}
}
22 changes: 22 additions & 0 deletions src/Symfony/Contracts/Tests/Service/ServiceSubscriberTraitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use Symfony\Contracts\Service\Attribute\Required;
use Symfony\Contracts\Service\Attribute\SubscribedService;
use Symfony\Contracts\Service\ServiceLocatorTrait;
use Symfony\Contracts\Service\ServiceProviderInterface;
use Symfony\Contracts\Service\ServiceSubscriberInterface;
use Symfony\Contracts\Service\ServiceSubscriberTrait;

Expand All @@ -26,6 +27,8 @@ class ServiceSubscriberTraitTest extends TestCase
public function testMethodsOnParentsAndChildrenAreIgnoredInGetSubscribedServices()
{
$expected = [
'service1' => Service1::class,
'service2' => '?'.Service2::class,
TestService::class.'::aService' => Service2::class,
TestService::class.'::nullableService' => '?'.Service2::class,
new SubscribedService(TestService::class.'::withAttribute', Service2::class, true, new Required()),
Expand Down Expand Up @@ -68,6 +71,19 @@ public function testParentNotCalledIfNoParent()
$this->assertNull($service->setContainer($container));
$this->assertSame([], $service::getSubscribedServices());
}

public function testCanGetSubscribedServiceProperties()
{
$factories = ['service1' => fn () => new Service1(), 'somethingElse' => fn () => new Service2()];
$container = new class($factories) implements ServiceProviderInterface {
use ServiceLocatorTrait;
};
$service = new TestService();
$service->setContainer($container);

$this->assertInstanceOf(Service1::class, $service->service1);
$this->assertNull($service->service2);
}
}

class ParentTestService
Expand All @@ -86,6 +102,12 @@ class TestService extends ParentTestService implements ServiceSubscriberInterfac
{
use ServiceSubscriberTrait;

#[SubscribedService]
public Service1 $service1;

#[SubscribedService]
public ?Service2 $service2;

#[SubscribedService]
public function aService(): Service2
{
Expand Down
0