Skip to content

[DependencyInjection] Add #[AutowireIterator] attribute and improve #[AutowireLocator] #51832

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

Merged
merged 2 commits into from
Oct 6, 2023
Merged
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
@@ -0,0 +1,77 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\DependencyInjection\Attribute;

use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\TypedReference;
use Symfony\Contracts\Service\Attribute\SubscribedService;
use Symfony\Contracts\Service\ServiceSubscriberInterface;

/**
* Autowires an iterator of services based on a tag name or an explicit list of key => service-type pairs.
*/
#[\Attribute(\Attribute::TARGET_PARAMETER)]
class AutowireIterator extends Autowire
{
/**
* @see ServiceSubscriberInterface::getSubscribedServices()
*
* @param string|array<string|SubscribedService> $services A tag name or an explicit list of services
* @param string|string[] $exclude A service or a list of services to exclude
*/
public function __construct(
string|array $services,
string $indexAttribute = null,
string $defaultIndexMethod = null,
string $defaultPriorityMethod = null,
string|array $exclude = [],
bool $excludeSelf = true,
) {
if (\is_string($services)) {
parent::__construct(new TaggedIteratorArgument($services, $indexAttribute, $defaultIndexMethod, false, $defaultPriorityMethod, (array) $exclude, $excludeSelf));

return;
}

$references = [];

foreach ($services as $key => $type) {
$attributes = [];

if ($type instanceof SubscribedService) {
$key = $type->key ?? $key;
$attributes = $type->attributes;
Copy link
Contributor

@bendavies bendavies Oct 12, 2023

Choose a reason for hiding this comment

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

symfony/dependency-injection requires "symfony/service-contracts": "^2.5|^3.0, but attributes, nullable and type are not defined on SubscribedService in until 3.2.
is this a mistake?

$type = ($type->nullable ? '?' : '').($type->type ?? throw new InvalidArgumentException(sprintf('When "%s" is used, a type must be set.', SubscribedService::class)));
}

if (!\is_string($type) || !preg_match('/(?(DEFINE)(?<cn>[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+))(?(DEFINE)(?<fqcn>(?&cn)(?:\\\\(?&cn))*+))^\??(?&fqcn)(?:(?:\|(?&fqcn))*+|(?:&(?&fqcn))*+)$/', $type)) {
throw new InvalidArgumentException(sprintf('"%s" is not a PHP type for key "%s".', \is_string($type) ? $type : get_debug_type($type), $key));
}
$optionalBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
if ('?' === $type[0]) {
$type = substr($type, 1);
$optionalBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
}
if (\is_int($name = $key)) {
$key = $type;
$name = null;
}

$references[$key] = new TypedReference($type, $type, $optionalBehavior, $name, $attributes);
}

parent::__construct(new IteratorArgument($references));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,32 +11,40 @@

namespace Symfony\Component\DependencyInjection\Attribute;

use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\Argument\ServiceLocatorArgument;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument;
use Symfony\Contracts\Service\Attribute\SubscribedService;
use Symfony\Contracts\Service\ServiceSubscriberInterface;

/**
* Autowires a service locator based on a tag name or an explicit list of key => service-type pairs.
*/
#[\Attribute(\Attribute::TARGET_PARAMETER)]
class AutowireLocator extends Autowire
{
public function __construct(string ...$serviceIds)
{
$values = [];

foreach ($serviceIds as $key => $serviceId) {
if ($nullable = str_starts_with($serviceId, '?')) {
$serviceId = substr($serviceId, 1);
}

if (is_numeric($key)) {
$key = $serviceId;
}

$values[$key] = new Reference(
$serviceId,
$nullable ? ContainerInterface::IGNORE_ON_INVALID_REFERENCE : ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE,
);
/**
* @see ServiceSubscriberInterface::getSubscribedServices()
*
* @param string|array<string|SubscribedService> $services An explicit list of services or a tag name
* @param string|string[] $exclude A service or a list of services to exclude
*/
public function __construct(
string|array $services,
string $indexAttribute = null,
string $defaultIndexMethod = null,
string $defaultPriorityMethod = null,
string|array $exclude = [],
bool $excludeSelf = true,
) {
$iterator = (new AutowireIterator($services, $indexAttribute, $defaultIndexMethod, $defaultPriorityMethod, (array) $exclude, $excludeSelf))->value;

if ($iterator instanceof TaggedIteratorArgument) {
$iterator = new TaggedIteratorArgument($iterator->getTag(), $iterator->getIndexAttribute(), $iterator->getDefaultIndexMethod(), true, $iterator->getDefaultPriorityMethod(), $iterator->getExclude(), $iterator->excludeSelf());
} elseif ($iterator instanceof IteratorArgument) {
$iterator = $iterator->getValues();
}

parent::__construct(new ServiceLocatorArgument($values));
parent::__construct(new ServiceLocatorArgument($iterator));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,8 @@

namespace Symfony\Component\DependencyInjection\Attribute;

use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument;

#[\Attribute(\Attribute::TARGET_PARAMETER)]
class TaggedIterator extends Autowire
class TaggedIterator extends AutowireIterator
{
public function __construct(
public string $tag,
Expand All @@ -24,6 +22,6 @@ public function __construct(
public string|array $exclude = [],
public bool $excludeSelf = true,
) {
parent::__construct(new TaggedIteratorArgument($tag, $indexAttribute, $defaultIndexMethod, false, $defaultPriorityMethod, (array) $exclude, $excludeSelf));
parent::__construct($tag, $indexAttribute, $defaultIndexMethod, $defaultPriorityMethod, $exclude, $excludeSelf);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,8 @@

namespace Symfony\Component\DependencyInjection\Attribute;

use Symfony\Component\DependencyInjection\Argument\ServiceLocatorArgument;
use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument;

#[\Attribute(\Attribute::TARGET_PARAMETER)]
class TaggedLocator extends Autowire
class TaggedLocator extends AutowireLocator
{
public function __construct(
public string $tag,
Expand All @@ -25,6 +22,6 @@ public function __construct(
public string|array $exclude = [],
public bool $excludeSelf = true,
) {
parent::__construct(new ServiceLocatorArgument(new TaggedIteratorArgument($tag, $indexAttribute, $defaultIndexMethod, true, $defaultPriorityMethod, (array) $exclude, $excludeSelf)));
parent::__construct($tag, $indexAttribute, $defaultIndexMethod, $defaultPriorityMethod, $exclude, $excludeSelf);
}
}
2 changes: 1 addition & 1 deletion src/Symfony/Component/DependencyInjection/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ CHANGELOG
* Allow using `#[Target]` with no arguments to state that a parameter must match a named autowiring alias
* Deprecate `ContainerAwareInterface` and `ContainerAwareTrait`, use dependency injection instead
* Add `defined` env var processor that returns `true` for defined and neither null nor empty env vars
* Add `#[AutowireLocator]` attribute
* Add `#[AutowireLocator]` and `#[AutowireIterator]` attributes

6.3
---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,15 +79,16 @@ protected function processValue(mixed $value, bool $isRoot = false): mixed
$attributes = [];

if ($type instanceof SubscribedService) {
$key = $type->key;
$key = $type->key ?? $key;
$attributes = $type->attributes;
$type = ($type->nullable ? '?' : '').($type->type ?? throw new InvalidArgumentException(sprintf('When "%s::getSubscribedServices()" returns "%s", a type must be set.', $class, SubscribedService::class)));
}

if (!\is_string($type) || !preg_match('/(?(DEFINE)(?<cn>[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+))(?(DEFINE)(?<fqcn>(?&cn)(?:\\\\(?&cn))*+))^\??(?&fqcn)(?:(?:\|(?&fqcn))*+|(?:&(?&fqcn))*+)$/', $type)) {
throw new InvalidArgumentException(sprintf('"%s::getSubscribedServices()" must return valid PHP types for service "%s" key "%s", "%s" returned.', $class, $this->currentId, $key, \is_string($type) ? $type : get_debug_type($type)));
}
if ($optionalBehavior = '?' === $type[0]) {
$optionalBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
if ('?' === $type[0]) {
$type = substr($type, 1);
$optionalBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
}
Expand Down Expand Up @@ -120,7 +121,7 @@ protected function processValue(mixed $value, bool $isRoot = false): mixed
$name = $this->container->has($type.' $'.$camelCaseName) ? $camelCaseName : $name;
}

$subscriberMap[$key] = new TypedReference((string) $serviceMap[$key], $type, $optionalBehavior ?: ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $name, $attributes);
$subscriberMap[$key] = new TypedReference((string) $serviceMap[$key], $type, $optionalBehavior, $name, $attributes);
unset($serviceMap[$key]);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,33 +15,33 @@
use Symfony\Component\DependencyInjection\Argument\ServiceLocatorArgument;
use Symfony\Component\DependencyInjection\Attribute\AutowireLocator;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\TypedReference;

class AutowireLocatorTest extends TestCase
{
public function testSimpleLocator()
{
$locator = new AutowireLocator('foo', 'bar');
$locator = new AutowireLocator(['foo', 'bar']);

$this->assertEquals(
new ServiceLocatorArgument(['foo' => new Reference('foo'), 'bar' => new Reference('bar')]),
new ServiceLocatorArgument(['foo' => new TypedReference('foo', 'foo'), 'bar' => new TypedReference('bar', 'bar')]),
$locator->value,
);
}

public function testComplexLocator()
{
$locator = new AutowireLocator(
$locator = new AutowireLocator([
'?qux',
foo: 'bar',
bar: '?baz',
);
'foo' => 'bar',
'bar' => '?baz',
]);

$this->assertEquals(
new ServiceLocatorArgument([
'qux' => new Reference('qux', ContainerInterface::IGNORE_ON_INVALID_REFERENCE),
'foo' => new Reference('bar'),
'bar' => new Reference('baz', ContainerInterface::IGNORE_ON_INVALID_REFERENCE),
'qux' => new TypedReference('qux', 'qux', ContainerInterface::IGNORE_ON_INVALID_REFERENCE),
'foo' => new TypedReference('bar', 'bar', name: 'foo'),
'bar' => new TypedReference('baz', 'baz', ContainerInterface::IGNORE_ON_INVALID_REFERENCE, 'bar'),
]),
$locator->value,
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Psr\Container\ContainerInterface;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
use Symfony\Component\DependencyInjection\Argument\ServiceLocatorArgument;
use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument;
use Symfony\Component\DependencyInjection\ChildDefinition;
Expand All @@ -32,6 +33,7 @@
use Symfony\Component\DependencyInjection\Tests\Fixtures\AutoconfiguredInterface2;
use Symfony\Component\DependencyInjection\Tests\Fixtures\AutoconfiguredService1;
use Symfony\Component\DependencyInjection\Tests\Fixtures\AutoconfiguredService2;
use Symfony\Component\DependencyInjection\Tests\Fixtures\AutowireIteratorConsumer;
use Symfony\Component\DependencyInjection\Tests\Fixtures\AutowireLocatorConsumer;
use Symfony\Component\DependencyInjection\Tests\Fixtures\BarTagClass;
use Symfony\Component\DependencyInjection\Tests\Fixtures\FooBarTaggedClass;
Expand Down Expand Up @@ -392,6 +394,7 @@ public function testTaggedServiceWithIndexAttributeAndDefaultMethod()
public function testLocatorConfiguredViaAttribute()
{
$container = new ContainerBuilder();
$container->setParameter('some.parameter', 'foo');
$container->register(BarTagClass::class)
->setPublic(true)
;
Expand All @@ -411,6 +414,36 @@ public function testLocatorConfiguredViaAttribute()
self::assertSame($container->get(BarTagClass::class), $s->locator->get(BarTagClass::class));
self::assertSame($container->get(FooTagClass::class), $s->locator->get('with_key'));
self::assertFalse($s->locator->has('nullable'));
self::assertSame('foo', $s->locator->get('subscribed'));
}

public function testIteratorConfiguredViaAttribute()
{
$container = new ContainerBuilder();
$container->setParameter('some.parameter', 'foo');
$container->register(BarTagClass::class)
->setPublic(true)
;
$container->register(FooTagClass::class)
->setPublic(true)
;
$container->register(AutowireIteratorConsumer::class)
->setAutowired(true)
->setPublic(true)
;

$container->compile();

/** @var AutowireIteratorConsumer $s */
$s = $container->get(AutowireIteratorConsumer::class);

self::assertInstanceOf(RewindableGenerator::class, $s->iterator);

$values = iterator_to_array($s->iterator);
self::assertCount(3, $values);
self::assertSame($container->get(BarTagClass::class), $values[BarTagClass::class]);
self::assertSame($container->get(FooTagClass::class), $values['with_key']);
self::assertSame('foo', $values['subscribed']);
}

public function testTaggedServiceWithIndexAttributeAndDefaultMethodConfiguredViaAttribute()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\DependencyInjection\Tests\Fixtures;

use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\DependencyInjection\Attribute\AutowireIterator;
use Symfony\Contracts\Service\Attribute\SubscribedService;

final class AutowireIteratorConsumer
{
public function __construct(
#[AutowireIterator([
BarTagClass::class,
'with_key' => FooTagClass::class,
'nullable' => '?invalid',
'subscribed' => new SubscribedService(type: 'string', attributes: new Autowire('%some.parameter%')),
])]
public readonly iterable $iterator,
) {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,19 @@
namespace Symfony\Component\DependencyInjection\Tests\Fixtures;

use Psr\Container\ContainerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\DependencyInjection\Attribute\AutowireLocator;
use Symfony\Contracts\Service\Attribute\SubscribedService;

final class AutowireLocatorConsumer
{
public function __construct(
#[AutowireLocator(
#[AutowireLocator([
BarTagClass::class,
with_key: FooTagClass::class,
nullable: '?invalid',
)]
'with_key' => FooTagClass::class,
'nullable' => '?invalid',
'subscribed' => new SubscribedService(type: 'string', attributes: new Autowire('%some.parameter%')),
])]
public readonly ContainerInterface $locator,
) {
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@

namespace Symfony\Component\DependencyInjection\Tests\Fixtures;

use Symfony\Component\DependencyInjection\Attribute\TaggedIterator;
use Symfony\Component\DependencyInjection\Attribute\AutowireIterator;

final class TaggedIteratorConsumer
{
public function __construct(
#[TaggedIterator('foo_bar', indexAttribute: 'foo')]
#[AutowireIterator('foo_bar', indexAttribute: 'foo')]
private iterable $param,
) {
}
Expand Down
Loading