Skip to content

[DI] added possibility to define services with abstract arguments #35076

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
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,44 @@
<?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\Argument;

/**
* Represents an abstract service argument, which have to be set by a compiler pass or a DI extension.
*/
final class AbstractArgument
{
private $serviceId;
private $argKey;
private $text;

public function __construct(string $serviceId, string $argKey, string $text = '')
{
$this->serviceId = $serviceId;
$this->argKey = $argKey;
$this->text = $text;
}

public function getServiceId(): string
{
return $this->serviceId;
}

public function getArgumentKey(): string
{
return $this->argKey;
}

public function getText(): string
{
return $this->text;
}
}
1 change: 1 addition & 0 deletions src/Symfony/Component/DependencyInjection/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ CHANGELOG

* added support to autowire public typed properties in php 7.4
* added support for defining method calls, a configurator, and property setters in `InlineServiceConfigurator`
* added possibility to define abstract service arguments

5.0.0
-----
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use Symfony\Component\Config\Resource\GlobResource;
use Symfony\Component\Config\Resource\ReflectionClassResource;
use Symfony\Component\Config\Resource\ResourceInterface;
use Symfony\Component\DependencyInjection\Argument\AbstractArgument;
use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
Expand Down Expand Up @@ -1215,6 +1216,8 @@ private function doResolveServices($value, array &$inlineServices = [], bool $is
$value = $this->getParameter((string) $value);
} elseif ($value instanceof Expression) {
$value = $this->getExpressionLanguage()->evaluate($value, ['container' => $this]);
} elseif ($value instanceof AbstractArgument) {
throw new RuntimeException(sprintf('Argument "%s" of service "%s" is abstract%s, did you forget to define it?', $value->getArgumentKey(), $value->getServiceId(), $value->getText() ? ' ('.$value->getText().')' : ''));
}

return $value;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use Composer\Autoload\ClassLoader;
use Symfony\Component\Debug\DebugClassLoader as LegacyDebugClassLoader;
use Symfony\Component\DependencyInjection\Argument\AbstractArgument;
use Symfony\Component\DependencyInjection\Argument\ArgumentInterface;
use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
Expand Down Expand Up @@ -1739,6 +1740,8 @@ private function dumpValue($value, bool $interpolate = true): string

return $code;
}
} elseif ($value instanceof AbstractArgument) {
throw new RuntimeException(sprintf('Argument "%s" of service "%s" is abstract%s, did you forget to define it?', $value->getArgumentKey(), $value->getServiceId(), $value->getText() ? ' ('.$value->getText().')' : ''));
} elseif (\is_object($value) || \is_resource($value)) {
throw new RuntimeException('Unable to dump a service container if a parameter is an object or a resource.');
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\DependencyInjection\Dumper;

use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Argument\AbstractArgument;
use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
use Symfony\Component\DependencyInjection\Argument\ServiceLocatorArgument;
Expand Down Expand Up @@ -312,6 +313,14 @@ private function convertParameters(array $parameters, string $type, \DOMElement
$element->setAttribute('type', 'binary');
$text = $this->document->createTextNode(self::phpToXml(base64_encode($value)));
$element->appendChild($text);
} elseif ($value instanceof AbstractArgument) {
$argKey = $value->getArgumentKey();
if (!is_numeric($argKey)) {
$element->setAttribute('key', $argKey);
}
$element->setAttribute('type', 'abstract');
$text = $this->document->createTextNode(self::phpToXml($value->getText()));
$element->appendChild($text);
} else {
if (\in_array($value, ['null', 'true', 'false'], true)) {
$element->setAttribute('type', 'string');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\DependencyInjection\Dumper;

use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Argument\AbstractArgument;
use Symfony\Component\DependencyInjection\Argument\ArgumentInterface;
use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
Expand Down Expand Up @@ -284,6 +285,8 @@ private function dumpValue($value)
return $this->getExpressionCall((string) $value);
} elseif ($value instanceof Definition) {
return new TaggedValue('service', (new Parser())->parse("_:\n".$this->addService('_', $value), Yaml::PARSE_CUSTOM_TAGS)['_']['_']);
} elseif ($value instanceof AbstractArgument) {
return new TaggedValue('abstract', $value->getText());
} elseif (\is_object($value) || \is_resource($value)) {
throw new RuntimeException('Unable to dump a service container if a parameter is an object or a resource.');
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use Symfony\Component\Config\Util\XmlUtils;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Argument\AbstractArgument;
use Symfony\Component\DependencyInjection\Argument\BoundArgument;
use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\Argument\ServiceLocatorArgument;
Expand Down Expand Up @@ -537,6 +538,10 @@ private function getArgumentsAsPhp(\DOMElement $node, string $name, string $file
}
$arguments[$key] = $value;
break;
case 'abstract':
$serviceId = $node->getAttribute('id');
$arguments[$key] = new AbstractArgument($serviceId, (string) $key, $arg->nodeValue);
break;
case 'string':
$arguments[$key] = $arg->nodeValue;
break;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\DependencyInjection\Loader;

use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Argument\AbstractArgument;
use Symfony\Component\DependencyInjection\Argument\ArgumentInterface;
use Symfony\Component\DependencyInjection\Argument\BoundArgument;
use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
Expand Down Expand Up @@ -446,7 +447,7 @@ private function parseDefinition(string $id, $service, string $file, array $defa
}

if (isset($service['arguments'])) {
$definition->setArguments($this->resolveServices($service['arguments'], $file));
$definition->setArguments($this->resolveServices($service['arguments'], $file, false, $id));
}

if (isset($service['properties'])) {
Expand Down Expand Up @@ -722,7 +723,7 @@ private function validate($content, string $file): ?array
*
* @return array|string|Reference|ArgumentInterface
*/
private function resolveServices($value, string $file, bool $isParameter = false)
private function resolveServices($value, string $file, bool $isParameter = false, string $serviceId = '', string $argKey = '')
{
if ($value instanceof TaggedValue) {
$argument = $value->getValue();
Expand Down Expand Up @@ -795,13 +796,16 @@ private function resolveServices($value, string $file, bool $isParameter = false

return new Reference($id);
}
if ('abstract' === $value->getTag()) {
return new AbstractArgument($serviceId, $argKey, $value->getValue());
}

throw new InvalidArgumentException(sprintf('Unsupported tag "!%s".', $value->getTag()));
}

if (\is_array($value)) {
foreach ($value as $k => $v) {
$value[$k] = $this->resolveServices($v, $file, $isParameter);
$value[$k] = $this->resolveServices($v, $file, $isParameter, $serviceId, $k);
}
} elseif (\is_string($value) && 0 === strpos($value, '@=')) {
if (!class_exists(Expression::class)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,7 @@

<xsd:simpleType name="argument_type">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="abstract" />
<xsd:enumeration value="collection" />
<xsd:enumeration value="service" />
<xsd:enumeration value="expression" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?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\Tests\Argument;

use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Argument\AbstractArgument;

class AbstractArgumentTest extends TestCase
{
public function testAbstractArgumentGetters()
{
$argument = new AbstractArgument('foo', '$bar', 'should be defined by Pass');
$this->assertSame('foo', $argument->getServiceId());
$this->assertSame('$bar', $argument->getArgumentKey());
$this->assertSame('should be defined by Pass', $argument->getText());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\Config\Resource\ResourceInterface;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Argument\AbstractArgument;
use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
Expand All @@ -41,6 +42,7 @@
use Symfony\Component\DependencyInjection\Tests\Compiler\Wither;
use Symfony\Component\DependencyInjection\Tests\Fixtures\CaseSensitiveClass;
use Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition;
use Symfony\Component\DependencyInjection\Tests\Fixtures\FooWithAbstractArgument;
use Symfony\Component\DependencyInjection\Tests\Fixtures\ScalarFactory;
use Symfony\Component\DependencyInjection\Tests\Fixtures\SimilarArgumentsDummy;
use Symfony\Component\DependencyInjection\TypedReference;
Expand Down Expand Up @@ -542,6 +544,18 @@ public function testCreateServiceWithExpression()
$this->assertEquals('foobar', $builder->get('foo')->arguments['foo']);
}

public function testCreateServiceWithAbstractArgument()
{
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('Argument "$baz" of service "foo" is abstract (should be defined by Pass), did you forget to define it?');

$builder = new ContainerBuilder();
$builder->register('foo', FooWithAbstractArgument::class)
->addArgument(new AbstractArgument('foo', '$baz', 'should be defined by Pass'));

$builder->get('foo');
}

public function testResolveServices()
{
$builder = new ContainerBuilder();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Psr\Container\ContainerInterface;
use Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper\ProxyDumper;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Argument\AbstractArgument;
use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
Expand All @@ -33,6 +34,7 @@
use Symfony\Component\DependencyInjection\Tests\Compiler\Foo;
use Symfony\Component\DependencyInjection\Tests\Compiler\Wither;
use Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition;
use Symfony\Component\DependencyInjection\Tests\Fixtures\FooWithAbstractArgument;
use Symfony\Component\DependencyInjection\Tests\Fixtures\ScalarFactory;
use Symfony\Component\DependencyInjection\Tests\Fixtures\StubbedTranslator;
use Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber;
Expand Down Expand Up @@ -1363,6 +1365,24 @@ public function testMultipleDeprecatedAliasesWorking()
$this->assertInstanceOf(\stdClass::class, $container->get('deprecated1'));
$this->assertInstanceOf(\stdClass::class, $container->get('deprecated2'));
}

public function testDumpServiceWithAbstractArgument()
{
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('Argument "$baz" of service "Symfony\Component\DependencyInjection\Tests\Fixtures\FooWithAbstractArgument" is abstract (should be defined by Pass), did you forget to define it?');

$container = new ContainerBuilder();

$container->register(FooWithAbstractArgument::class, FooWithAbstractArgument::class)
->setArgument('$baz', new AbstractArgument(FooWithAbstractArgument::class, '$baz', 'should be defined by Pass'))
->setArgument('$bar', 'test')
->setPublic(true);

$container->compile();

$dumper = new PhpDumper($container);
$dumper->dump();
}
}

class Rot13EnvVarProcessor implements EnvVarProcessorInterface
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,15 @@

use PHPUnit\Framework\TestCase;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Argument\AbstractArgument;
use Symfony\Component\DependencyInjection\Argument\ServiceLocatorArgument;
use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Dumper\XmlDumper;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Tests\Fixtures\FooWithAbstractArgument;

class XmlDumperTest extends TestCase
{
Expand Down Expand Up @@ -237,4 +239,15 @@ public function testDumpAbstractServices()

$this->assertEquals(file_get_contents(self::$fixturesPath.'/xml/services_abstract.xml'), $dumper->dump());
}

public function testDumpServiceWithAbstractArgument()
{
$container = new ContainerBuilder();
$container->register(FooWithAbstractArgument::class, FooWithAbstractArgument::class)
->setArgument('$baz', new AbstractArgument(FooWithAbstractArgument::class, '$baz', 'should be defined by Pass'))
->setArgument('$bar', 'test');

$dumper = new XmlDumper($container);
$this->assertStringEqualsFile(self::$fixturesPath.'/xml/services_with_abstract_argument.xml', $dumper->dump());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use PHPUnit\Framework\TestCase;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Argument\AbstractArgument;
use Symfony\Component\DependencyInjection\Argument\ServiceLocatorArgument;
use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument;
use Symfony\Component\DependencyInjection\ContainerBuilder;
Expand All @@ -21,6 +22,7 @@
use Symfony\Component\DependencyInjection\Dumper\YamlDumper;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Tests\Fixtures\FooWithAbstractArgument;
use Symfony\Component\Yaml\Parser;
use Symfony\Component\Yaml\Yaml;

Expand Down Expand Up @@ -117,6 +119,17 @@ public function testTaggedArguments()
$this->assertStringEqualsFile(self::$fixturesPath.'/yaml/services_with_tagged_argument.yml', $dumper->dump());
}

public function testDumpServiceWithAbstractArgument()
{
$container = new ContainerBuilder();
$container->register(FooWithAbstractArgument::class, FooWithAbstractArgument::class)
->setArgument('$baz', new AbstractArgument(FooWithAbstractArgument::class, '$baz', 'should be defined by Pass'))
->setArgument('$bar', 'test');

$dumper = new YamlDumper($container);
$this->assertStringEqualsFile(self::$fixturesPath.'/yaml/services_with_abstract_argument.yml', $dumper->dump());
}

private function assertEqualYamlStructure(string $expected, string $yaml, string $message = '')
{
$parser = new Parser();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace Symfony\Component\DependencyInjection\Tests\Fixtures;

class FooWithAbstractArgument
{
/** @var string */
private $baz;

/** @var string */
private $bar;

public function __construct(string $baz, string $bar)
{
$this->baz = $baz;
$this->bar = $bar;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?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="Symfony\Component\DependencyInjection\Tests\Fixtures\FooWithAbstractArgument">
<argument key="$baz" type="abstract">should be defined by FooCompilerPass</argument>
<argument key="$bar">test</argument>
</service>
</services>
</container>
Loading