Skip to content

Commit 8ce7016

Browse files
committed
feature #45657 [DependencyInjection] add Autowire parameter attribute (kbond)
This PR was merged into the 6.1 branch. Discussion ---------- [DependencyInjection] add `Autowire` parameter attribute | Q | A | ------------- | --- | Branch? | 6.1 | Bug fix? | no | New feature? | yes | Deprecations? | no | Tickets | n/a | License | MIT | Doc PR | todo Replaces #45573 & #44780 with a single new `Autowire` attribute: ```php class MyService { public function __construct( #[Autowire(service: 'some_service')] private $service1, #[Autowire(expression: 'service("App\\Mail\\MailerConfiguration").getMailerMethod()') private $service2, #[Autowire(value: '%env(json:file:resolve:AUTH_FILE)%')] private $parameter1, #[Autowire(value: '%kernel.project_dir%/config/dir')] private $parameter2, ) {} } ``` Works with controller arguments as well: ```php class MyController { public function someAction( #[Autowire(service: 'some_service')] $service1, #[Autowire(expression: 'service("App\\Mail\\MailerConfiguration").getMailerMethod()') $service2, #[Autowire(value: '%env(json:file:resolve:AUTH_FILE)%')] $parameter1, #[Autowire(value: '%kernel.project_dir%/config/dir')] $parameter2, ): Response {} } ``` Commits ------- d43fe42109 [DependencyInjection] add `Autowire` parameter attribute
2 parents f4ac533 + 84b5696 commit 8ce7016

File tree

2 files changed

+66
-1
lines changed

2 files changed

+66
-1
lines changed

DependencyInjection/RegisterControllerArgumentLocatorsPass.php

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
namespace Symfony\Component\HttpKernel\DependencyInjection;
1313

1414
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
15+
use Symfony\Component\DependencyInjection\Attribute\Autowire;
1516
use Symfony\Component\DependencyInjection\Attribute\Target;
1617
use Symfony\Component\DependencyInjection\ChildDefinition;
1718
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
@@ -49,6 +50,8 @@ public function process(ContainerBuilder $container)
4950
}
5051
}
5152

53+
$emptyAutowireAttributes = class_exists(Autowire::class) ? null : [];
54+
5255
foreach ($container->findTaggedServiceIds('controller.service_arguments', true) as $id => $tags) {
5356
$def = $container->getDefinition($id);
5457
$def->setPublic(true);
@@ -122,6 +125,7 @@ public function process(ContainerBuilder $container)
122125
/** @var \ReflectionParameter $p */
123126
$type = ltrim($target = (string) ProxyHelper::getTypeHint($r, $p), '\\');
124127
$invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
128+
$autowireAttributes = $autowire ? $emptyAutowireAttributes : [];
125129

126130
if (isset($arguments[$r->name][$p->name])) {
127131
$target = $arguments[$r->name][$p->name];
@@ -148,7 +152,7 @@ public function process(ContainerBuilder $container)
148152
}
149153

150154
continue;
151-
} elseif (!$type || !$autowire || '\\' !== $target[0]) {
155+
} elseif (!$autowire || (!($autowireAttributes ??= $p->getAttributes(Autowire::class)) && (!$type || '\\' !== $target[0]))) {
152156
continue;
153157
} elseif (is_subclass_of($type, \UnitEnum::class)) {
154158
// do not attempt to register enum typed arguments if not already present in bindings
@@ -161,6 +165,21 @@ public function process(ContainerBuilder $container)
161165
continue;
162166
}
163167

168+
if ($autowireAttributes) {
169+
$value = $autowireAttributes[0]->newInstance()->value;
170+
171+
if ($value instanceof Reference) {
172+
$args[$p->name] = $type ? new TypedReference($value, $type, $invalidBehavior, $p->name) : new Reference($value, $invalidBehavior);
173+
} else {
174+
$args[$p->name] = new Reference('.value.'.$container->hash($value));
175+
$container->register((string) $args[$p->name], 'mixed')
176+
->setFactory('current')
177+
->addArgument([$value]);
178+
}
179+
180+
continue;
181+
}
182+
164183
if ($type && !$p->isOptional() && !$p->allowsNull() && !class_exists($type) && !interface_exists($type, false)) {
165184
$message = sprintf('Cannot determine controller argument for "%s::%s()": the $%s argument is type-hinted with the non-existent class or interface: "%s".', $class, $r->name, $p->name, $type);
166185

Tests/DependencyInjection/RegisterControllerArgumentLocatorsPassTest.php

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
use PHPUnit\Framework\TestCase;
1515
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
16+
use Symfony\Component\DependencyInjection\Attribute\Autowire;
1617
use Symfony\Component\DependencyInjection\Attribute\Target;
1718
use Symfony\Component\DependencyInjection\ChildDefinition;
1819
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
@@ -441,6 +442,36 @@ public function testBindWithTarget()
441442
];
442443
$this->assertEquals($expected, $locator->getArgument(0));
443444
}
445+
446+
public function testAutowireAttribute()
447+
{
448+
if (!class_exists(Autowire::class)) {
449+
$this->markTestSkipped('#[Autowire] attribute not available.');
450+
}
451+
452+
$container = new ContainerBuilder();
453+
$resolver = $container->register('argument_resolver.service', 'stdClass')->addArgument([]);
454+
455+
$container->register('some.id', \stdClass::class);
456+
$container->setParameter('some.parameter', 'foo');
457+
458+
$container->register('foo', WithAutowireAttribute::class)
459+
->addTag('controller.service_arguments');
460+
461+
(new RegisterControllerArgumentLocatorsPass())->process($container);
462+
463+
$locatorId = (string) $resolver->getArgument(0);
464+
$container->getDefinition($locatorId)->setPublic(true);
465+
466+
$container->compile();
467+
468+
$locator = $container->get($locatorId)->get('foo::fooAction');
469+
470+
$this->assertInstanceOf(\stdClass::class, $locator->get('service1'));
471+
$this->assertSame('foo/bar', $locator->get('value'));
472+
$this->assertSame('foo', $locator->get('expression'));
473+
$this->assertFalse($locator->has('service2'));
474+
}
444475
}
445476

446477
class RegisterTestController
@@ -521,3 +552,18 @@ public function fooAction(
521552
) {
522553
}
523554
}
555+
556+
class WithAutowireAttribute
557+
{
558+
public function fooAction(
559+
#[Autowire(service: 'some.id')]
560+
\stdClass $service1,
561+
#[Autowire(value: '%some.parameter%/bar')]
562+
string $value,
563+
#[Autowire(expression: "parameter('some.parameter')")]
564+
string $expression,
565+
#[Autowire(service: 'invalid.id')]
566+
\stdClass $service2 = null,
567+
) {
568+
}
569+
}

0 commit comments

Comments
 (0)