Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[DependencyInjection] Add #[AutowireMethodOf] attribute to autowire a method of a service as a callable #54016

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
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,38 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* 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\Definition;
use Symfony\Component\DependencyInjection\Reference;

/**
* Tells which method should be turned into a Closure based on the name of the parameter it's attached to.
*/
#[\Attribute(\Attribute::TARGET_PARAMETER)]
class AutowireMethodOf extends AutowireCallable
{
/**
* @param string $service The service containing the method to autowire
* @param bool|class-string $lazy Whether to use lazy-loading for this argument
*/
public function __construct(string $service, bool|string $lazy = false)
{
parent::__construct([new Reference($service)], lazy: $lazy);
}

public function buildDefinition(mixed $value, ?string $type, \ReflectionParameter $parameter): Definition
{
$value[1] = $parameter->name;

return parent::buildDefinition($value, $type, $parameter);
}
}
1 change: 1 addition & 0 deletions src/Symfony/Component/DependencyInjection/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ CHANGELOG
* Add argument `$prepend` to `ContainerConfigurator::extension()` to prepend the configuration instead of appending it
* Have `ServiceLocator` implement `ServiceCollectionInterface`
* Add `#[Lazy]` attribute as shortcut for `#[Autowire(lazy: [bool|string])]` and `#[Autoconfigure(lazy: [bool|string])]`
* Add `#[AutowireMethodOf]` attribute to autowire a method of a service as a callable

7.0
---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ protected function processValue(mixed $value, bool $isRoot = false): mixed
if (!$value instanceof Reference) {
return parent::processValue($value, $isRoot);
}
if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE < $value->getInvalidBehavior() || $this->container->has($id = (string) $value)) {
if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE < $value->getInvalidBehavior() || $this->container->has((string) $value)) {
return $value;
}

Expand Down Expand Up @@ -83,7 +83,7 @@ protected function processValue(mixed $value, bool $isRoot = false): mixed
$this->throwServiceNotFoundException($value, $currentId, $value);
}

private function throwServiceNotFoundException(Reference $ref, string $sourceId, $value): void
private function throwServiceNotFoundException(Reference $ref, string $sourceId, mixed $value): void
{
$id = (string) $ref;
$alternatives = [];
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

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

namespace Symfony\Component\DependencyInjection\Tests\Attribute;

use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Attribute\AutowireMethodOf;
use Symfony\Component\DependencyInjection\Reference;

class AutowireMethodOfTest extends TestCase
{
public function testConstructor()
{
$a = new AutowireMethodOf('foo');

$this->assertEquals([new Reference('foo')], $a->value);
}

public function testBuildDefinition(?\Closure $dummy = null)
{
$a = new AutowireMethodOf('foo');
$r = new \ReflectionParameter([__CLASS__, __FUNCTION__], 0);

$this->assertEquals([[new Reference('foo'), 'dummy']], $a->buildDefinition($a->value, 'Closure', $r)->getArguments());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,10 @@ public function resolve(Request $request, ArgumentMetadata $argument): array
try {
return [$this->container->get($controller)->get($argument->getName())];
} catch (RuntimeException $e) {
$what = sprintf('argument $%s of "%s()"', $argument->getName(), $controller);
$message = preg_replace('/service "\.service_locator\.[^"]++"/', $what, $e->getMessage());
$what = 'argument $'.$argument->getName();
$message = str_replace(sprintf('service "%s"', $argument->getName()), $what, $e->getMessage());
$what .= sprintf(' of "%s()"', $controller);
$message = preg_replace('/service "\.service_locator\.[^"]++"/', $what, $message);

if ($e->getMessage() === $message) {
$message = sprintf('Cannot resolve %s: %s', $what, $message);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ public function process(ContainerBuilder $container): void

// create a per-method map of argument-names to service/type-references
$args = [];
$erroredIds = 0;
foreach ($parameters as $p) {
/** @var \ReflectionParameter $p */
$type = preg_replace('/(^|[(|&])\\\\/', '\1', $target = ltrim(ProxyHelper::exportType($p) ?? '', '?'));
Expand Down Expand Up @@ -171,10 +172,8 @@ public function process(ContainerBuilder $container): void
$value = $parameterBag->resolveValue($attribute->value);

if ($attribute instanceof AutowireCallable) {
$value = $attribute->buildDefinition($value, $type, $p);
}

if ($value instanceof Reference) {
$args[$p->name] = $attribute->buildDefinition($value, $type, $p);
} elseif ($value instanceof Reference) {
$args[$p->name] = $type ? new TypedReference($value, $type, $invalidBehavior, $p->name) : new Reference($value, $invalidBehavior);
} else {
$args[$p->name] = new Reference('.value.'.$container->hash($value));
Expand All @@ -198,14 +197,15 @@ public function process(ContainerBuilder $container): void
->addError($message);

$args[$p->name] = new Reference($erroredId, ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE);
++$erroredIds;
} else {
$target = preg_replace('/(^|[(|&])\\\\/', '\1', $target);
$args[$p->name] = $type ? new TypedReference($target, $type, $invalidBehavior, Target::parseName($p)) : new Reference($target, $invalidBehavior);
}
}
// register the maps as a per-method service-locators
if ($args) {
$controllers[$id.'::'.$r->name] = ServiceLocatorTagPass::register($container, $args);
$controllers[$id.'::'.$r->name] = ServiceLocatorTagPass::register($container, $args, \count($args) !== $erroredIds ? $id.'::'.$r->name.'()' : null);

foreach ($publicAliases[$id] ?? [] as $alias) {
$controllers[$alias.'::'.$r->name] = clone $controllers[$id.'::'.$r->name];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ public function process(ContainerBuilder $container): void
foreach ($controllers as $controller => $argumentRef) {
$argumentLocator = $container->getDefinition((string) $argumentRef->getValues()[0]);

if ($argumentLocator->getFactory()) {
$argumentLocator = $container->getDefinition($argumentLocator->getFactory()[0]);
}

if (!$argumentLocator->getArgument(0)) {
// remove empty argument locators
$reason = sprintf('Removing service-argument resolver for controller "%s": no corresponding services exist for the referenced types.', $controller);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ public function testControllerNameIsAnArray()
public function testErrorIsTruncated()
{
$this->expectException(NearMissValueResolverException::class);
$this->expectExceptionMessage('Cannot autowire argument $dummy of "Symfony\Component\HttpKernel\Tests\Controller\ArgumentResolver\DummyController::index()": it references class "Symfony\Component\HttpKernel\Tests\Controller\ArgumentResolver\DummyService" but no such service exists.');
$this->expectExceptionMessage('Cannot autowire argument $dummy required by "Symfony\Component\HttpKernel\Tests\Controller\ArgumentResolver\DummyController::index()": it references class "Symfony\Component\HttpKernel\Tests\Controller\ArgumentResolver\DummyService" but no such service exists.');
$container = new ContainerBuilder();
$container->addCompilerPass(new RegisterControllerArgumentLocatorsPass());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ public function testAllActions()
$this->assertInstanceof(ServiceClosureArgument::class, $locator['foo::fooAction']);

$locator = $container->getDefinition((string) $locator['foo::fooAction']->getValues()[0]);
$locator = $container->getDefinition((string) $locator->getFactory()[0]);

$this->assertSame(ServiceLocator::class, $locator->getClass());
$this->assertFalse($locator->isPublic());
Expand All @@ -166,6 +167,7 @@ public function testExplicitArgument()

$locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
$locator = $container->getDefinition((string) $locator['foo::fooAction']->getValues()[0]);
$locator = $container->getDefinition((string) $locator->getFactory()[0]);

$expected = ['bar' => new ServiceClosureArgument(new TypedReference('bar', ControllerDummy::class, ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE))];
$this->assertEquals($expected, $locator->getArgument(0));
Expand All @@ -185,6 +187,7 @@ public function testOptionalArgument()

$locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
$locator = $container->getDefinition((string) $locator['foo::fooAction']->getValues()[0]);
$locator = $container->getDefinition((string) $locator->getFactory()[0]);

$expected = ['bar' => new ServiceClosureArgument(new TypedReference('bar', ControllerDummy::class, ContainerInterface::IGNORE_ON_INVALID_REFERENCE))];
$this->assertEquals($expected, $locator->getArgument(0));
Expand Down Expand Up @@ -306,8 +309,8 @@ public function testBindings($bindingName)
$pass->process($container);

$locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);

$locator = $container->getDefinition((string) $locator['foo::fooAction']->getValues()[0]);
$locator = $container->getDefinition((string) $locator->getFactory()[0]);

$expected = ['bar' => new ServiceClosureArgument(new Reference('foo'))];
$this->assertEquals($expected, $locator->getArgument(0));
Expand Down Expand Up @@ -372,7 +375,8 @@ public function testBindingsOnChildDefinitions()
$locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
$this->assertInstanceOf(ServiceClosureArgument::class, $locator['child::fooAction']);

$locator = $container->getDefinition((string) $locator['child::fooAction']->getValues()[0])->getArgument(0);
$locator = $container->getDefinition((string) $locator['child::fooAction']->getValues()[0]);
$locator = $container->getDefinition((string) $locator->getFactory()[0])->getArgument(0);
$this->assertInstanceOf(ServiceClosureArgument::class, $locator['someArg']);
$this->assertEquals(new Reference('parent'), $locator['someArg']->getValues()[0]);
}
Expand Down Expand Up @@ -439,6 +443,7 @@ public function testBindWithTarget()

$locator = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
$locator = $container->getDefinition((string) $locator['foo::fooAction']->getValues()[0]);
$locator = $container->getDefinition((string) $locator->getFactory()[0]);

$expected = [
'apiKey' => new ServiceClosureArgument(new Reference('the_api_key')),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,22 +35,23 @@ public function testProcess()
$pass->process($container);

$controllers = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);
$getLocator = fn ($controllers, $k) => $container->getDefinition((string) $container->getDefinition((string) $controllers[$k]->getValues()[0])->getFactory()[0])->getArgument(0);

$this->assertCount(2, $container->getDefinition((string) $controllers['c1::fooAction']->getValues()[0])->getArgument(0));
$this->assertCount(1, $container->getDefinition((string) $controllers['c2::setTestCase']->getValues()[0])->getArgument(0));
$this->assertCount(1, $container->getDefinition((string) $controllers['c2::fooAction']->getValues()[0])->getArgument(0));
$this->assertCount(2, $getLocator($controllers, 'c1::fooAction'));
$this->assertCount(1, $getLocator($controllers, 'c2::setTestCase'));
$this->assertCount(1, $getLocator($controllers, 'c2::fooAction'));

(new ResolveInvalidReferencesPass())->process($container);

$this->assertCount(1, $container->getDefinition((string) $controllers['c2::setTestCase']->getValues()[0])->getArgument(0));
$this->assertSame([], $container->getDefinition((string) $controllers['c2::fooAction']->getValues()[0])->getArgument(0));
$this->assertCount(1, $getLocator($controllers, 'c2::setTestCase'));
$this->assertSame([], $getLocator($controllers, 'c2::fooAction'));

(new RemoveEmptyControllerArgumentLocatorsPass())->process($container);

$controllers = $container->getDefinition((string) $resolver->getArgument(0))->getArgument(0);

$this->assertSame(['c1::fooAction', 'c1:fooAction'], array_keys($controllers));
$this->assertSame(['bar'], array_keys($container->getDefinition((string) $controllers['c1::fooAction']->getValues()[0])->getArgument(0)));
$this->assertSame(['bar'], array_keys($getLocator($controllers, 'c1::fooAction')));

$expectedLog = [
'Symfony\Component\HttpKernel\DependencyInjection\RemoveEmptyControllerArgumentLocatorsPass: Removing service-argument resolver for controller "c2::fooAction": no corresponding services exist for the referenced types.',
Expand Down