Skip to content

[DependencyInjection] Allow using expressions as service factories #45512

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 26, 2022
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
5 changes: 5 additions & 0 deletions UPGRADE-6.1.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ Console
* Add argument `$suggestedValues` to `Command::addArgument` and `Command::addOption`
* Add argument `$suggestedValues` to `InputArgument` and `InputOption` constructors

DependencyInjection
-------------------

* Deprecate `ReferenceSetArgumentTrait`

FrameworkBundle
---------------

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,20 @@
*/
class IteratorArgument implements ArgumentInterface
{
use ReferenceSetArgumentTrait;
private array $values;

public function __construct(array $values)
{
$this->setValues($values);
}

public function getValues(): array
{
return $this->values;
}

public function setValues(array $values)
{
$this->values = $values;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,16 @@

namespace Symfony\Component\DependencyInjection\Argument;

trigger_deprecation('symfony/dependency-injection', '6.1', '"%s" is deprecated.', ReferenceSetArgumentTrait::class);

use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Reference;

/**
* @author Titouan Galopin <galopintitouan@gmail.com>
* @author Nicolas Grekas <p@tchwork.com>
*
* @deprecated since Symfony 6.1
*/
trait ReferenceSetArgumentTrait
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
namespace Symfony\Component\DependencyInjection\Argument;

use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Reference;

/**
* Represents a service wrapped in a memoizing closure.
Expand All @@ -23,9 +22,9 @@ class ServiceClosureArgument implements ArgumentInterface
{
private array $values;

public function __construct(Reference $reference)
public function __construct(mixed $value)
{
$this->values = [$reference];
$this->values = [$value];
}

/**
Expand All @@ -41,8 +40,8 @@ public function getValues(): array
*/
public function setValues(array $values)
{
if ([0] !== array_keys($values) || !($values[0] instanceof Reference || null === $values[0])) {
throw new InvalidArgumentException('A ServiceClosureArgument must hold one and only one Reference.');
if ([0] !== array_keys($values)) {
throw new InvalidArgumentException('A ServiceClosureArgument must hold one and only one value.');
}

$this->values = $values;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,11 @@ public function __construct(\Closure $factory, array $serviceMap, array $service
*/
public function get(string $id): mixed
{
return isset($this->serviceMap[$id]) ? ($this->factory)(...$this->serviceMap[$id]) : parent::get($id);
return match (\count($this->serviceMap[$id] ?? [])) {
0 => parent::get($id),
1 => $this->serviceMap[$id][0],
default => ($this->factory)(...$this->serviceMap[$id]),
};
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,34 +11,38 @@

namespace Symfony\Component\DependencyInjection\Argument;

use Symfony\Component\DependencyInjection\Reference;

/**
* Represents a closure acting as a service locator.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
class ServiceLocatorArgument implements ArgumentInterface
{
use ReferenceSetArgumentTrait;

private array $values;
private ?TaggedIteratorArgument $taggedIteratorArgument = null;

/**
* @param Reference[]|TaggedIteratorArgument $values
*/
public function __construct(array|TaggedIteratorArgument $values = [])
{
if ($values instanceof TaggedIteratorArgument) {
$this->taggedIteratorArgument = $values;
$this->values = [];
} else {
$this->setValues($values);
$values = [];
}

$this->setValues($values);
}

public function getTaggedIteratorArgument(): ?TaggedIteratorArgument
{
return $this->taggedIteratorArgument;
}

public function getValues(): array
{
return $this->values;
}

public function setValues(array $values)
{
$this->values = $values;
}
}
2 changes: 2 additions & 0 deletions src/Symfony/Component/DependencyInjection/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ CHANGELOG
* Add `$exclude` to `tagged_iterator` and `tagged_locator` configurator
* Add an `env` function to the expression language provider
* Add an `Autowire` attribute to tell a parameter how to be autowired
* Allow using expressions as service factories
* Deprecate `ReferenceSetArgumentTrait`

6.0
---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,15 +84,24 @@ protected function processValue(mixed $value, bool $isRoot = false)
} elseif ($value instanceof ArgumentInterface) {
$value->setValues($this->processValue($value->getValues()));
} elseif ($value instanceof Expression && $this->processExpressions) {
$this->getExpressionLanguage()->compile((string) $value, ['this' => 'container']);
$this->getExpressionLanguage()->compile((string) $value, ['this' => 'container', 'args' => 'args']);
} elseif ($value instanceof Definition) {
$value->setArguments($this->processValue($value->getArguments()));
$value->setProperties($this->processValue($value->getProperties()));
$value->setMethodCalls($this->processValue($value->getMethodCalls()));

$changes = $value->getChanges();
if (isset($changes['factory'])) {
$value->setFactory($this->processValue($value->getFactory()));
if (\is_string($factory = $value->getFactory()) && str_starts_with($factory, '@=')) {
if (!class_exists(Expression::class)) {
throw new LogicException('Expressions cannot be used in service factories without the ExpressionLanguage component. Try running "composer require symfony/expression-language".');
}
$factory = new Expression(substr($factory, 2));
}
if (($factory = $this->processValue($factory)) instanceof Expression) {
$factory = '@='.$factory;
}
$value->setFactory($factory);
}
if (isset($changes['configurator'])) {
$value->setConfigurator($this->processValue($value->getConfigurator()));
Expand All @@ -112,6 +121,10 @@ protected function getConstructor(Definition $definition, bool $required): ?\Ref
}

if (\is_string($factory = $definition->getFactory())) {
if (str_starts_with($factory, '@=')) {
return new \ReflectionFunction(static function (...$args) {});
}

if (!\function_exists($factory)) {
throw new RuntimeException(sprintf('Invalid service "%s": function "%s" does not exist.', $this->currentId, $factory));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\ExpressionLanguage\Expression;

/**
* Run this pass before passes that need to know more about the relation of
Expand Down Expand Up @@ -135,8 +137,16 @@ protected function processValue(mixed $value, bool $isRoot = false): mixed

$byFactory = $this->byFactory;
$this->byFactory = true;
$this->processValue($value->getFactory());
if (\is_string($factory = $value->getFactory()) && str_starts_with($factory, '@=')) {
if (!class_exists(Expression::class)) {
throw new LogicException('Expressions cannot be used in service factories without the ExpressionLanguage component. Try running "composer require symfony/expression-language".');
}

$factory = new Expression(substr($factory, 2));
}
$this->processValue($factory);
$this->byFactory = $byFactory;

$this->processValue($value->getArguments());

$properties = $value->getProperties();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,18 +64,17 @@ protected function processValue(mixed $value, bool $isRoot = false): mixed
if ($v instanceof ServiceClosureArgument) {
continue;
}
if (!$v instanceof Reference) {
throw new InvalidArgumentException(sprintf('Invalid definition for service "%s": an array of references is expected as first argument when the "container.service_locator" tag is set, "%s" found for key "%s".', $this->currentId, get_debug_type($v), $k));
}

if ($i === $k) {
unset($services[$k]);

$k = (string) $v;
if ($v instanceof Reference) {
unset($services[$k]);
$k = (string) $v;
}
++$i;
} elseif (\is_int($k)) {
$i = null;
}

$services[$k] = new ServiceClosureArgument($v);
}
ksort($services);
Expand All @@ -97,20 +96,14 @@ protected function processValue(mixed $value, bool $isRoot = false): mixed
return new Reference($id);
}

/**
* @param Reference[] $refMap
*/
public static function register(ContainerBuilder $container, array $refMap, string $callerId = null): Reference
public static function register(ContainerBuilder $container, array $map, string $callerId = null): Reference
{
foreach ($refMap as $id => $ref) {
if (!$ref instanceof Reference) {
throw new InvalidArgumentException(sprintf('Invalid service locator definition: only services can be referenced, "%s" found for key "%s". Inject parameter values using constructors instead.', get_debug_type($ref), $id));
}
$refMap[$id] = new ServiceClosureArgument($ref);
foreach ($map as $k => $v) {
$map[$k] = new ServiceClosureArgument($v);
}

$locator = (new Definition(ServiceLocator::class))
->addArgument($refMap)
->addArgument($map)
->addTag('container.service_locator');

if (null !== $callerId && $container->hasDefinition($callerId)) {
Expand Down
19 changes: 12 additions & 7 deletions src/Symfony/Component/DependencyInjection/ContainerBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -1008,16 +1008,23 @@ private function createService(Definition $definition, array &$inlineServices, b
require_once $parameterBag->resolveValue($definition->getFile());
}

$arguments = $this->doResolveServices($parameterBag->unescapeValue($parameterBag->resolveValue($definition->getArguments())), $inlineServices, $isConstructorArgument);
$arguments = $definition->getArguments();

if (null !== $factory = $definition->getFactory()) {
if (\is_array($factory)) {
$factory = [$this->doResolveServices($parameterBag->resolveValue($factory[0]), $inlineServices, $isConstructorArgument), $factory[1]];
} elseif (!\is_string($factory)) {
throw new RuntimeException(sprintf('Cannot create service "%s" because of invalid factory.', $id));
} elseif (str_starts_with($factory, '@=')) {
$factory = function (ServiceLocator $arguments) use ($factory) {
return $this->getExpressionLanguage()->evaluate(substr($factory, 2), ['container' => $this, 'args' => $arguments]);
};
$arguments = [new ServiceLocatorArgument($arguments)];
}
}

$arguments = $this->doResolveServices($parameterBag->unescapeValue($parameterBag->resolveValue($arguments)), $inlineServices, $isConstructorArgument);

if (null !== $id && $definition->isShared() && isset($this->services[$id]) && ($tryProxy || !$definition->isLazy())) {
return $this->services[$id];
}
Expand Down Expand Up @@ -1149,10 +1156,8 @@ private function doResolveServices(mixed $value, array &$inlineServices = [], bo
} elseif ($value instanceof ServiceLocatorArgument) {
$refs = $types = [];
foreach ($value->getValues() as $k => $v) {
if ($v) {
$refs[$k] = [$v];
$types[$k] = $v instanceof TypedReference ? $v->getType() : '?';
}
$refs[$k] = [$v, null];
$types[$k] = $v instanceof TypedReference ? $v->getType() : '?';
}
$value = new ServiceLocator($this->resolveServices(...), $refs, $types);
} elseif ($value instanceof Reference) {
Expand Down Expand Up @@ -1583,8 +1588,8 @@ private function shareService(Definition $definition, mixed $service, ?string $i
private function getExpressionLanguage(): ExpressionLanguage
{
if (!isset($this->expressionLanguage)) {
if (!class_exists(\Symfony\Component\ExpressionLanguage\ExpressionLanguage::class)) {
throw new LogicException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
if (!class_exists(Expression::class)) {
throw new LogicException('Expressions cannot be used without the ExpressionLanguage component. Try running "composer require symfony/expression-language".');
}
$this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders, null, $this->getEnv(...));
}
Expand Down
15 changes: 12 additions & 3 deletions src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php
Original file line number Diff line number Diff line change
Expand Up @@ -806,7 +806,7 @@ private function addService(string $id, Definition $definition): array
$return[] = sprintf(str_starts_with($class, '%') ? '@return object A %1$s instance' : '@return \%s', ltrim($class, '\\'));
} elseif ($definition->getFactory()) {
$factory = $definition->getFactory();
if (\is_string($factory)) {
if (\is_string($factory) && !str_starts_with($factory, '@=')) {
$return[] = sprintf('@return object An instance returned by %s()', $factory);
} elseif (\is_array($factory) && (\is_string($factory[0]) || $factory[0] instanceof Definition || $factory[0] instanceof Reference)) {
$class = $factory[0] instanceof Definition ? $factory[0]->getClass() : (string) $factory[0];
Expand Down Expand Up @@ -1159,6 +1159,13 @@ private function addNewInstance(Definition $definition, string $return = '', str
return $return.sprintf("[%s, '%s'](%s)", $class, $callable[1], $arguments ? implode(', ', $arguments) : '').$tail;
}

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

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

Expand Down Expand Up @@ -1740,7 +1747,7 @@ private function dumpValue(mixed $value, bool $interpolate = true): string
$code = sprintf('return %s;', $code);

$attribute = '';
if ($value) {
if ($value instanceof Reference) {
$attribute = 'name: '.$this->dumpValue((string) $value, $interpolate);

if ($this->container->hasDefinition($value) && ($class = $this->container->findDefinition($value)->getClass()) && $class !== (string) $value) {
Expand Down Expand Up @@ -1787,7 +1794,9 @@ private function dumpValue(mixed $value, bool $interpolate = true): string
$serviceMap = '';
$serviceTypes = '';
foreach ($value->getValues() as $k => $v) {
if (!$v) {
if (!$v instanceof Reference) {
$serviceMap .= sprintf("\n %s => [%s],", $this->export($k), $this->dumpValue($v));
$serviceTypes .= sprintf("\n %s => '?',", $this->export($k));
continue;
}
$id = (string) $v;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,9 @@ private function convertParameters(array $parameters, string $type, \DOMElement
} elseif ($value instanceof ServiceLocatorArgument) {
$element->setAttribute('type', 'service_locator');
$this->convertParameters($value->getValues(), $type, $element, 'key');
} elseif ($value instanceof ServiceClosureArgument && !$value->getValues()[0] instanceof Reference) {
$element->setAttribute('type', 'service_closure');
$this->convertParameters($value->getValues(), $type, $element, 'key');
} elseif ($value instanceof Reference || $value instanceof ServiceClosureArgument) {
$element->setAttribute('type', 'service');
if ($value instanceof ServiceClosureArgument) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ private function dumpValue(mixed $value): mixed
if ($value instanceof ServiceClosureArgument) {
$value = $value->getValues()[0];

return new TaggedValue('service_closure', $this->getServiceCall((string) $value, $value));
return new TaggedValue('service_closure', $this->dumpValue($value));
}
if ($value instanceof ArgumentInterface) {
$tag = $value;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,12 @@ public function getFunctions(): array

return ($this->getEnv)($value);
}),

new ExpressionFunction('arg', function ($arg) {
return sprintf('$args?->get(%s)', $arg);
}, function (array $variables, $value) {
return $variables['args']?->get($value);
}),
];
}
}
Loading