Skip to content

[DependencyInjection] Add support for casting callables into single-method interfaces #49632

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 1 commit into from
Mar 28, 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
43 changes: 36 additions & 7 deletions src/Symfony/Component/DependencyInjection/Argument/LazyClosure.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,11 @@

namespace Symfony\Component\DependencyInjection\Argument;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\VarExporter\ProxyHelper;

/**
Expand Down Expand Up @@ -44,17 +47,43 @@ public function __get(mixed $name): mixed
return $this->service;
}

public static function getCode(string $initializer, ?\ReflectionClass $r, string $method, ?string $id): string
public static function getCode(string $initializer, array $callable, Definition $definition, ContainerBuilder $container, ?string $id): string
{
if (!$r || !$r->hasMethod($method)) {
$method = $callable[1];
$asClosure = 'Closure' === ($definition->getClass() ?: 'Closure');

if ($asClosure) {
$class = ($callable[0] instanceof Reference ? $container->findDefinition($callable[0]) : $callable[0])->getClass();
} else {
$class = $definition->getClass();
}

$r = $container->getReflectionClass($class);

if (!$asClosure) {
if (!$r || !$r->isInterface()) {
throw new RuntimeException(sprintf('Cannot create adapter for service "%s" because "%s" is not an interface.', $id, $class));
}
if (1 !== \count($method = $r->getMethods())) {
throw new RuntimeException(sprintf('Cannot create adapter for service "%s" because interface "%s" doesn\'t have exactly one method.', $id, $class));
}
$method = $method[0]->name;
} elseif (!$r || !$r->hasMethod($method)) {
throw new RuntimeException(sprintf('Cannot create lazy closure for service "%s" because its corresponding callable is invalid.', $id));
}

$signature = ProxyHelper::exportSignature($r->getMethod($method));
$signature = preg_replace('/: static$/', ': \\'.$r->name, $signature);
$code = ProxyHelper::exportSignature($r->getMethod($method));

if ($asClosure) {
$code = ' { '.preg_replace('/: static$/', ': \\'.$r->name, $code);
} else {
$code = ' implements \\'.$r->name.' { '.$code;
}

$code = 'new class('.$initializer.') extends \\'.self::class
.$code.' { return $this->service->'.$callable[1].'(...\func_get_args()); } '
.'}';

return '(new class('.$initializer.') extends \\'.self::class.' { '
.$signature.' { return $this->service->'.$method.'(...\func_get_args()); } '
.'})->'.$method.'(...)';
return $asClosure ? '('.$code.')->'.$method.'(...)' : $code;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,14 @@
#[\Attribute(\Attribute::TARGET_PARAMETER)]
class AutowireCallable extends Autowire
{
/**
* @param bool|class-string $lazy Whether to use lazy-loading for this argument
*/
public function __construct(
string|array $callable = null,
string $service = null,
string $method = null,
bool $lazy = false,
bool|string $lazy = false,
) {
if (!(null !== $callable xor null !== $service)) {
throw new LogicException('#[AutowireCallable] attribute must declare exactly one of $callable or $service.');
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Component/DependencyInjection/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ CHANGELOG
* Add support for generating lazy closures
* Add support for autowiring services as closures using `#[AutowireCallable]` or `#[AutowireServiceClosure]`
* Add support for `#[Autowire(lazy: true|class-string)]`
* Make it possible to cast callables into single-method interfaces
* Deprecate `#[MapDecorated]`, use `#[AutowireDecorated]` instead
* Deprecate the `@required` annotation, use the `Symfony\Contracts\Service\Attribute\Required` attribute instead

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -291,10 +291,10 @@ private function autowireMethod(\ReflectionFunctionAbstract $reflectionMethod, a
$value = $this->processValue(new TypedReference($type ?: '?', $type ?: 'mixed', $invalidBehavior, $name, [$attribute, ...$target]));

if ($attribute instanceof AutowireCallable) {
$value = (new Definition('Closure'))
$value = (new Definition($type = \is_string($attribute->lazy) ? $attribute->lazy : ($type ?: 'Closure')))
->setFactory(['Closure', 'fromCallable'])
->setArguments([$value + [1 => '__invoke']])
->setLazy($attribute->lazy);
->setArguments([\is_array($value) ? $value + [1 => '__invoke'] : $value])
->setLazy($attribute->lazy || 'Closure' !== $type && 'callable' !== (string) $parameter->getType());
} elseif ($lazy = $attribute->lazy) {
$definition = (new Definition($type))
->setFactory('current')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1051,9 +1051,9 @@ private function createService(Definition $definition, array &$inlineServices, b
}

$parameterBag = $this->getParameterBag();
$class = ($parameterBag->resolveValue($definition->getClass()) ?: (['Closure', 'fromCallable'] === $definition->getFactory() ? 'Closure' : null));
$class = $parameterBag->resolveValue($definition->getClass()) ?: (['Closure', 'fromCallable'] === $definition->getFactory() ? 'Closure' : null);

if ('Closure' === $class && $definition->isLazy() && ['Closure', 'fromCallable'] === $definition->getFactory()) {
if (['Closure', 'fromCallable'] === $definition->getFactory() && ('Closure' !== $class || $definition->isLazy())) {
$callable = $parameterBag->unescapeValue($parameterBag->resolveValue($definition->getArgument(0)));

if ($callable instanceof Reference || $callable instanceof Definition) {
Expand All @@ -1065,19 +1065,18 @@ private function createService(Definition $definition, array &$inlineServices, b
|| $callable[0] instanceof Definition && !isset($inlineServices[spl_object_hash($callable[0])])
)) {
$containerRef = $this->containerRef ??= \WeakReference::create($this);
$class = ($callable[0] instanceof Reference ? $this->findDefinition($callable[0]) : $callable[0])->getClass();
$initializer = static function () use ($containerRef, $callable, &$inlineServices) {
return $containerRef->get()->doResolveServices($callable[0], $inlineServices);
};

$proxy = eval('return '.LazyClosure::getCode('$initializer', $this->getReflectionClass($class), $callable[1], $id).';');
$proxy = eval('return '.LazyClosure::getCode('$initializer', $callable, $definition, $this, $id).';');
$this->shareService($definition, $proxy, $id, $inlineServices);

return $proxy;
}
}

if (true === $tryProxy && $definition->isLazy() && 'Closure' !== $class
if (true === $tryProxy && $definition->isLazy() && ['Closure', 'fromCallable'] !== $definition->getFactory()
&& !$tryProxy = !($proxy = $this->proxyInstantiator ??= new LazyServiceInstantiator()) || $proxy instanceof RealServiceInstantiator
) {
$containerRef = $this->containerRef ??= \WeakReference::create($this);
Expand Down
81 changes: 40 additions & 41 deletions src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php
Original file line number Diff line number Diff line change
Expand Up @@ -1162,7 +1162,8 @@ private function addNewInstance(Definition $definition, string $return = '', str
if ('current' === $callable && [0] === array_keys($definition->getArguments()) && \is_array($value) && [0] === array_keys($value)) {
return $return.$this->dumpValue($value[0]).$tail;
}
if (['Closure', 'fromCallable'] === $callable && [0] === array_keys($definition->getArguments())) {

if (['Closure', 'fromCallable'] === $callable) {
$callable = $definition->getArgument(0);
if ($callable instanceof ServiceClosureArgument) {
return $return.$this->dumpValue($callable).$tail;
Expand All @@ -1175,58 +1176,56 @@ private function addNewInstance(Definition $definition, string $return = '', str
}
}

if (\is_array($callable)) {
if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $callable[1])) {
throw new RuntimeException(sprintf('Cannot dump definition because of invalid factory method (%s).', $callable[1] ?: 'n/a'));
}

if (['...'] === $arguments && $definition->isLazy() && 'Closure' === ($definition->getClass() ?? 'Closure') && (
$callable[0] instanceof Reference
|| ($callable[0] instanceof Definition && !$this->definitionVariables->contains($callable[0]))
)) {
$class = ($callable[0] instanceof Reference ? $this->container->findDefinition($callable[0]) : $callable[0])->getClass();
if (\is_string($callable) && str_starts_with($callable, '@=')) {
return $return.sprintf('(($args = %s) ? (%s) : null)',
$this->dumpValue(new ServiceLocatorArgument($definition->getArguments())),
$this->getExpressionLanguage()->compile(substr($callable, 2), ['container' => 'container', 'args' => 'args'])
).$tail;
}

if (str_contains($initializer = $this->dumpValue($callable[0]), '$container')) {
$this->addContainerRef = true;
$initializer = sprintf('function () use ($containerRef) { $container = $containerRef; return %s; }', $initializer);
} else {
$initializer = 'fn () => '.$initializer;
}
if (!\is_array($callable)) {
return $return.sprintf('%s(%s)', $this->dumpLiteralClass($this->dumpValue($callable)), $arguments ? implode(', ', $arguments) : '').$tail;
}

return $return.LazyClosure::getCode($initializer, $this->container->getReflectionClass($class), $callable[1], $id).$tail;
}
if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $callable[1])) {
throw new RuntimeException(sprintf('Cannot dump definition because of invalid factory method (%s).', $callable[1] ?: 'n/a'));
}

if ($callable[0] instanceof Reference
|| ($callable[0] instanceof Definition && $this->definitionVariables->contains($callable[0]))
) {
return $return.sprintf('%s->%s(%s)', $this->dumpValue($callable[0]), $callable[1], $arguments ? implode(', ', $arguments) : '').$tail;
if (['...'] === $arguments && ($definition->isLazy() || 'Closure' !== ($definition->getClass() ?? 'Closure')) && (
$callable[0] instanceof Reference
|| ($callable[0] instanceof Definition && !$this->definitionVariables->contains($callable[0]))
)) {
if (str_contains($initializer = $this->dumpValue($callable[0]), '$container')) {
$this->addContainerRef = true;
$initializer = sprintf('function () use ($containerRef) { $container = $containerRef->get(); return %s; }', $initializer);
} else {
$initializer = 'fn () => '.$initializer;
}

$class = $this->dumpValue($callable[0]);
// If the class is a string we can optimize away
if (str_starts_with($class, "'") && !str_contains($class, '$')) {
if ("''" === $class) {
throw new RuntimeException(sprintf('Cannot dump definition: "%s" service is defined to be created by a factory but is missing the service reference, did you forget to define the factory service id or class?', $id ? 'The "'.$id.'"' : 'inline'));
}
return $return.LazyClosure::getCode($initializer, $callable, $definition, $this->container, $id).$tail;
}

return $return.sprintf('%s::%s(%s)', $this->dumpLiteralClass($class), $callable[1], $arguments ? implode(', ', $arguments) : '').$tail;
}
if ($callable[0] instanceof Reference
|| ($callable[0] instanceof Definition && $this->definitionVariables->contains($callable[0]))
) {
return $return.sprintf('%s->%s(%s)', $this->dumpValue($callable[0]), $callable[1], $arguments ? implode(', ', $arguments) : '').$tail;
}

if (str_starts_with($class, 'new ')) {
return $return.sprintf('(%s)->%s(%s)', $class, $callable[1], $arguments ? implode(', ', $arguments) : '').$tail;
$class = $this->dumpValue($callable[0]);
// If the class is a string we can optimize away
if (str_starts_with($class, "'") && !str_contains($class, '$')) {
if ("''" === $class) {
throw new RuntimeException(sprintf('Cannot dump definition: "%s" service is defined to be created by a factory but is missing the service reference, did you forget to define the factory service id or class?', $id ? 'The "'.$id.'"' : 'inline'));
}

return $return.sprintf("[%s, '%s'](%s)", $class, $callable[1], $arguments ? implode(', ', $arguments) : '').$tail;
return $return.sprintf('%s::%s(%s)', $this->dumpLiteralClass($class), $callable[1], $arguments ? implode(', ', $arguments) : '').$tail;
}

if (\is_string($callable) && str_starts_with($callable, '@=')) {
return $return.sprintf('(($args = %s) ? (%s) : null)',
$this->dumpValue(new ServiceLocatorArgument($definition->getArguments())),
$this->getExpressionLanguage()->compile(substr($callable, 2), ['container' => 'container', 'args' => 'args'])
).$tail;
if (str_starts_with($class, 'new ')) {
return $return.sprintf('(%s)->%s(%s)', $class, $callable[1], $arguments ? implode(', ', $arguments) : '').$tail;
}

return $return.sprintf('%s(%s)', $this->dumpLiteralClass($this->dumpValue($callable)), $arguments ? implode(', ', $arguments) : '').$tail;
return $return.sprintf("[%s, '%s'](%s)", $class, $callable[1], $arguments ? implode(', ', $arguments) : '').$tail;
}

if (null === $class = $definition->getClass()) {
Expand Down Expand Up @@ -2344,7 +2343,7 @@ private function isProxyCandidate(Definition $definition, ?bool &$asGhostObject,
{
$asGhostObject = false;

if ('Closure' === ($definition->getClass() ?: (['Closure', 'fromCallable'] === $definition->getFactory() ? 'Closure' : null))) {
if (['Closure', 'fromCallable'] === $definition->getFactory()) {
return null;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?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\Loader\Configurator;

use Symfony\Component\DependencyInjection\Definition;

/**
* @author Nicolas Grekas <p@tchwork.com>
*/
class FromCallableConfigurator extends AbstractServiceConfigurator
{
use Traits\AbstractTrait;
use Traits\AutoconfigureTrait;
use Traits\AutowireTrait;
use Traits\BindTrait;
use Traits\DecorateTrait;
use Traits\DeprecateTrait;
use Traits\LazyTrait;
use Traits\PublicTrait;
use Traits\ShareTrait;
use Traits\TagTrait;

public const FACTORY = 'services';

private ServiceConfigurator $serviceConfigurator;

public function __construct(ServiceConfigurator $serviceConfigurator, Definition $definition)
{
$this->serviceConfigurator = $serviceConfigurator;

parent::__construct($serviceConfigurator->parent, $definition, $serviceConfigurator->id);
}

public function __destruct()
{
$this->serviceConfigurator->__destruct();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ class ServiceConfigurator extends AbstractServiceConfigurator
use Traits\DeprecateTrait;
use Traits\FactoryTrait;
use Traits\FileTrait;
use Traits\FromCallableTrait;
use Traits\LazyTrait;
use Traits\ParentTrait;
use Traits\PropertyTrait;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?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\Loader\Configurator\Traits;

use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Loader\Configurator\FromCallableConfigurator;
use Symfony\Component\DependencyInjection\Loader\Configurator\ReferenceConfigurator;
use Symfony\Component\ExpressionLanguage\Expression;

trait FromCallableTrait
{
final public function fromCallable(string|array|ReferenceConfigurator|Expression $callable): FromCallableConfigurator
{
if ($this->definition instanceof ChildDefinition) {
throw new InvalidArgumentException('The configuration key "parent" is unsupported when using "fromCallable()".');
}

foreach ([
'synthetic' => 'isSynthetic',
'factory' => 'getFactory',
'file' => 'getFile',
'arguments' => 'getArguments',
'properties' => 'getProperties',
'configurator' => 'getConfigurator',
'calls' => 'getMethodCalls',
] as $key => $method) {
if ($this->definition->$method()) {
throw new InvalidArgumentException(sprintf('The configuration key "%s" is unsupported when using "fromCallable()".', $key));
}
}

$this->definition->setFactory(['Closure', 'fromCallable']);

if (\is_string($callable) && 1 === substr_count($callable, ':')) {
$parts = explode(':', $callable);

throw new InvalidArgumentException(sprintf('Invalid callable "%s": the "service:method" notation is not available when using PHP-based DI configuration. Use "[service(\'%s\'), \'%s\']" instead.', $callable, $parts[0], $parts[1]));
}

if ($callable instanceof Expression) {
$callable = '@='.$callable;
}

$this->definition->setArguments([static::processValue($callable, true)]);

if ('Closure' !== ($this->definition->getClass() ?? 'Closure')) {
$this->definition->setLazy(true);
} else {
$this->definition->setClass('Closure');
}

return new FromCallableConfigurator($this, $this->definition);
}
}
Loading