Skip to content

[DependencyInjection] Add argument type closure to help passing closures to services #45878

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 30, 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
1 change: 1 addition & 0 deletions src/Symfony/Component/DependencyInjection/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ CHANGELOG
* 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
* Add argument type `closure` to help passing closures to services
* Deprecate `ReferenceSetArgumentTrait`

6.0
Expand Down
11 changes: 10 additions & 1 deletion src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php
Original file line number Diff line number Diff line change
Expand Up @@ -1132,6 +1132,15 @@ private function addNewInstance(Definition $definition, string $return = '', str
if (null !== $definition->getFactory()) {
$callable = $definition->getFactory();

if (['Closure', 'fromCallable'] === $callable && [0] === array_keys($definition->getArguments())) {
$callable = $definition->getArgument(0);
$arguments = ['...'];

if ($callable instanceof Reference || $callable instanceof Definition) {
$callable = [$callable, '__invoke'];
}
}

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'));
Expand Down Expand Up @@ -1159,7 +1168,7 @@ 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, '@=')) {
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), ['this' => 'container', 'args' => 'args'])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -183,3 +183,13 @@ function service_closure(string $serviceId): ClosureReferenceConfigurator
{
return new ClosureReferenceConfigurator($serviceId);
}

/**
* Creates a closure.
*/
function closure(string|array|ReferenceConfigurator|Expression $callable): InlineServiceConfigurator
{
return (new InlineServiceConfigurator(new Definition('Closure')))
->factory(['Closure', 'fromCallable'])
->args([$callable]);
}
Original file line number Diff line number Diff line change
Expand Up @@ -495,7 +495,7 @@ private function getArgumentsAsPhp(\DOMElement $node, string $name, string $file
$invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE;
}

switch ($arg->getAttribute('type')) {
switch ($type = $arg->getAttribute('type')) {
case 'service':
if ('' === $arg->getAttribute('id')) {
throw new InvalidArgumentException(sprintf('Tag "<%s>" with type="service" has no or empty "id" attribute in "%s".', $name, $file));
Expand All @@ -517,13 +517,19 @@ private function getArgumentsAsPhp(\DOMElement $node, string $name, string $file
$arg = $this->getArgumentsAsPhp($arg, $name, $file);
$arguments[$key] = new IteratorArgument($arg);
break;
case 'closure':
case 'service_closure':
if ('' !== $arg->getAttribute('id')) {
$arg = new Reference($arg->getAttribute('id'), $invalidBehavior);
} else {
$arg = $this->getArgumentsAsPhp($arg, $name, $file);
}
$arguments[$key] = new ServiceClosureArgument($arg);
$arguments[$key] = match ($type) {
'service_closure' => new ServiceClosureArgument($arg),
'closure' => (new Definition('Closure'))
->setFactory(['Closure', 'fromCallable'])
->addArgument($arg),
};
break;
case 'service_locator':
$arg = $this->getArgumentsAsPhp($arg, $name, $file);
Expand All @@ -532,7 +538,6 @@ private function getArgumentsAsPhp(\DOMElement $node, string $name, string $file
case 'tagged':
case 'tagged_iterator':
case 'tagged_locator':
$type = $arg->getAttribute('type');
$forLocator = 'tagged_locator' === $type;

if (!$arg->getAttribute('tag')) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -804,6 +804,14 @@ private function resolveServices(mixed $value, string $file, bool $isParameter =
{
if ($value instanceof TaggedValue) {
$argument = $value->getValue();

if ('closure' === $value->getTag()) {
$argument = $this->resolveServices($argument, $file, $isParameter);

return (new Definition('Closure'))
->setFactory(['Closure', 'fromCallable'])
->addArgument($argument);
}
if ('iterator' === $value->getTag()) {
if (!\is_array($argument)) {
throw new InvalidArgumentException(sprintf('"!iterator" tag only accepts sequences in "%s".', $file));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,7 @@
<xsd:enumeration value="constant" />
<xsd:enumeration value="binary" />
<xsd:enumeration value="iterator" />
<xsd:enumeration value="closure" />
<xsd:enumeration value="service_closure" />
<xsd:enumeration value="service_locator" />
<!-- "tagged" is an alias of "tagged_iterator", using "tagged_iterator" is preferred. -->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1534,6 +1534,20 @@ public function testExpressionInFactory()

$this->assertSame(247, $container->get('foo')->bar);
}

public function testClosure()
{
$container = new ContainerBuilder();
$container->register('closure', 'Closure')
->setPublic('true')
->setFactory(['Closure', 'fromCallable'])
->setArguments([new Reference('bar')]);
$container->register('bar', 'stdClass');
$container->compile();
$dumper = new PhpDumper($container);

$this->assertStringEqualsFile(self::$fixturesPath.'/php/closure.php', $dumper->dump());
}
}

class Rot13EnvVarProcessor implements EnvVarProcessorInterface
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@

services:
service_container:
class: Symfony\Component\DependencyInjection\ContainerInterface
public: true
synthetic: true
closure_property:
class: stdClass
public: true
properties: { foo: !service { class: Closure, arguments: [!service { class: stdClass }], factory: [Closure, fromCallable] } }
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace Symfony\Component\DependencyInjection\Loader\Configurator;

return new class() {
public function __invoke(ContainerConfigurator $c)
{
$c->services()
->set('closure_property', 'stdClass')
->public()
->property('foo', closure(service('bar')))
->set('bar', 'stdClass');
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

/**
* @internal This class has been auto-generated by the Symfony Dependency Injection Component.
*/
class ProjectServiceContainer extends Container
{
protected $parameters = [];

public function __construct()
{
$this->services = $this->privates = [];
$this->methodMap = [
'closure' => 'getClosureService',
];

$this->aliases = [];
}

public function compile(): void
{
throw new LogicException('You cannot compile a dumped container that was already compiled.');
}

public function isCompiled(): bool
{
return true;
}

public function getRemovedIds(): array
{
return [
'bar' => true,
];
}

/**
* Gets the public 'closure' shared service.
*
* @return \Closure
*/
protected function getClosureService()
{
return $this->services['closure'] = (new \stdClass())->__invoke(...);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="closure_property" class="stdClass">
<property key="foo" type="closure" id="bar" />
</service>
</services>
</container>
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
services:
closure_property:
class: stdClass
properties: { foo: !closure '@bar' }
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ public function provideConfig()
yield ['remove'];
yield ['config_builder'];
yield ['expression_factory'];
yield ['closure'];
}

public function testAutoConfigureAndChildDefinition()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1113,4 +1113,14 @@ public function testWhenEnv()

$this->assertSame(['foo' => 234, 'bar' => 345], $container->getParameterBag()->all());
}

public function testClosure()
{
$container = new ContainerBuilder();
$loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
$loader->load('closure.xml');

$definition = $container->getDefinition('closure_property')->getProperties()['foo'];
$this->assertEquals((new Definition('Closure'))->setFactory(['Closure', 'fromCallable'])->addArgument(new Reference('bar')), $definition);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1088,4 +1088,14 @@ public function testWhenEnv()

$this->assertSame(['foo' => 234, 'bar' => 345], $container->getParameterBag()->all());
}

public function testClosure()
{
$container = new ContainerBuilder();
$loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
$loader->load('closure.yml');

$definition = $container->getDefinition('closure_property')->getProperties()['foo'];
$this->assertEquals((new Definition('Closure'))->setFactory(['Closure', 'fromCallable'])->addArgument(new Reference('bar')), $definition);
}
}