8000 [DependencyInjection] Add `constructor` option to `#[Autoconfigure]` by alexandre-daubois · Pull Request #49665 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[DependencyInjection] Add constructor option to #[Autoconfigure] #49665

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 31, 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
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ public function __construct(
public ?bool $autowire = null,
public ?array $properties = null,
public array|string|null $configurator = null,
public string|null $constructor = null,
) {
}
}
1 change: 1 addition & 0 deletions src/Symfony/Component/DependencyInjection/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ CHANGELOG
* 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
* Add `constructor` option to services declaration and to `#[Autoconfigure]`

6.2
---
Expand Down
28 changes: 16 additions & 12 deletions src/Symfony/Component/DependencyInjection/Dumper/XmlDumper.php
Original file line number Diff line number Diff line change
Expand Up @@ -167,20 +167,24 @@ private function addService(Definition $definition, ?string $id, \DOMElement $pa
$this->addMethodCalls($definition->getMethodCalls(), $service);

if ($callable = $definition->getFactory()) {
$factory = $this->document->createElement('factory');

if (\is_array($callable) && $callable[0] instanceof Definition) {
$this->addService($callable[0], null, $factory);
$factory->setAttribute('method', $callable[1]);
} elseif (\is_array($callable)) {
if (null !== $callable[0]) {
$factory->setAttribute($callable[0] instanceof Reference ? 'service' : 'class', $callable[0]);
}
$factory->setAttribute('method', $callable[1]);
if (\is_array($callable) && ['Closure', 'fromCallable'] !== $callable && $definition->getClass() === $callable[0]) {
$service->setAttribute('constructor', $callable[1]);
} else {
$factory->setAttribute('function', $callable);
$factory = $this->document->createElement('factory');

if (\is_array($callable) && $callable[0] instanceof Definition) {
$this->addService($callable[0], null, $factory);
$factory->setAttribute('method', $callable[1]);
} elseif (\is_array($callable)) {
if (null !== $callable[0]) {
$factory->setAttribute($callable[0] instanceof Reference ? 'service' : 'class', $callable[0]);
}
$factory->setAttribute('method', $callable[1]);
} else {
$factory->setAttribute('function', $callable);
}
$service->appendChild($factory);
}
$service->appendChild($factory);
}

if ($definition->isDeprecated()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,11 @@ private function addService(string $id, Definition $definition): string
}

if ($callable = $definition->getFactory()) {
$code .= sprintf(" factory: %s\n", $this->dumper->dump($this->dumpCallable($callable), 0));
if (\is_array($callable) && ['Closure', 'fromCallable'] !== $callable && $definition->getClass() === $callable[0]) {
$code .= sprintf(" constructor: %s\n", $callable[1]);
} else {
$code .= sprintf(" factory: %s\n", $this->dumper->dump($this->dumpCallable($callable), 0));
}
}

if ($callable = $definition->getConfigurator()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ class InlineServiceConfigurator extends AbstractConfigurator
use Traits\BindTrait;
use Traits\CallTrait;
use Traits\ConfiguratorTrait;
use Traits\ConstructorTrait;
use Traits\FactoryTrait;
use Traits\FileTrait;
use Traits\LazyTrait;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ class InstanceofConfigurator extends AbstractServiceConfigurator
use Traits\BindTrait;
use Traits\CallTrait;
use Traits\ConfiguratorTrait;
use Traits\ConstructorTrait;
use Traits\LazyTrait;
use Traits\PropertyTrait;
use Traits\PublicTrait;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ class PrototypeConfigurator extends AbstractServiceConfigurator
use Traits\BindTrait;
use Traits\CallTrait;
use Traits\ConfiguratorTrait;
use Traits\ConstructorTrait;
use Traits\DeprecateTrait;
use Traits\FactoryTrait;
use Traits\LazyTrait;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ class ServiceConfigurator extends AbstractServiceConfigurator
use Traits\CallTrait;
use Traits\ClassTrait;
use Traits\ConfiguratorTrait;
use Traits\ConstructorTrait;
use Traits\DecorateTrait;
use Traits\DeprecateTrait;
use Traits\FactoryTrait;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?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;

trait ConstructorTrait
{
/**
* Sets a static constructor.
*
* @return $this
*/
final public function constructor(string $constructor): static
{
$this->definition->setFactory([null, $constructor]);

return $this;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
use Symfony\Component\DependencyInjection\Reference;
Expand Down Expand Up @@ -314,6 +315,14 @@ private function parseDefinition(\DOMElement $service, string $file, Definition
}
}

if ($constructor = $service->getAttribute('constructor')) {
if (null !== $definition->getFactory()) {
throw new LogicException(sprintf('The "%s" service cannot declare a factory as well as a constructor.', $service->getAttribute('id')));
}

$definition->setFactory([null, $constructor]);
}

if ($configurators = $this->getChildren($service, 'configurator')) {
$configurator = $configurators[0];
if ($function = $configurator->getAttribute('function')) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
use Symfony\Component\DependencyInjection\Reference;
Expand Down Expand Up @@ -63,6 +64,7 @@ class YamlFileLoader extends FileLoader
'autowire' => 'autowire',
'autoconfigure' => 'autoconfigure',
'bind' => 'bind',
'constructor' => 'constructor',
];

private const PROTOTYPE_KEYWORDS = [
Expand All @@ -84,6 +86,7 @@ class YamlFileLoader extends FileLoader
'autowire' => 'autowire',
'autoconfigure' => 'autoconfigure',
'bind' => 'bind',
'constructor' => 'constructor',
];

private const INSTANCEOF_KEYWORDS = [
Expand All @@ -96,6 +99,7 @@ class YamlFileLoader extends FileLoader
'tags' => 'tags',
'autowire' => 'autowire',
'bind' => 'bind',
'constructor' => 'constructor',
];

private const DEFAULTS_KEYWORDS = [
Expand Down Expand Up @@ -517,6 +521,14 @@ private function parseDefinition(string $id, array|string|null $service, string
$definition->setFactory($this->parseCallable($service['factory'], 'factory', $id, $file));
}

if (isset($service['constructor'])) {
if (null !== $definition->getFactory()) {
throw new LogicException(sprintf('The "%s" service cannot declare a factory as well as a constructor.', $id));
}

$definition->setFactory([null, $service['constructor']]);
}

if (isset($service['file'])) {
$definition->setFile($service['file']);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@
<xsd:attribute name="decoration-priority" type="xsd:integer" />
<xsd:attribute name="autowire" type="boolean" />
<xsd:attribute name="autoconfigure" type="boolean" />
<xsd:attribute name="constructor" type="xsd:string" />
</xsd:complexType>

<xsd:complexType name="instanceof">
Expand All @@ -185,6 +186,7 @@
<xsd:attribute name="lazy" type="xsd:string" />
<xsd:attribute name="autowire" type="boolean" />
<xsd:attribute name="autoconfigure" type="boolean" />
<xsd:attribute name="constructor" type="xsd:string" />
</xsd:complexType>

<xsd:complexType name="prototype">
Expand All @@ -209,6 +211,7 @@
<xsd:attribute name="parent" type="xsd:string" />
<xsd:attribute name="autowire" type="boolean" />
<xsd:attribute name="autoconfigure" type="boolean" />
<xsd:attribute name="constructor" type="xsd:string" />
</xsd:complexType>

<xsd:complexType name="stack">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use Symfony\Component\DependencyInjection\Tests\Fixtures\AutoconfigureAttributed;
use Symfony\Component\DependencyInjection\Tests\Fixtures\AutoconfiguredInterface;
use Symfony\Component\DependencyInjection\Tests\Fixtures\ParentNotExists;
use Symfony\Component\DependencyInjection\Tests\Fixtures\StaticConstructorAutoconfigure;

class RegisterAutoconfigureAttributesPassTest extends TestCase
{
Expand Down Expand Up @@ -47,6 +48,7 @@ public function testProcess()
->addTag('another_tag', ['attr' => 234])
->addMethodCall('setBar', [2, 3])
->setBindings(['$bar' => $argument])
->setFactory([null, 'create'])
;
$this->assertEquals([AutoconfigureAttributed::class => $expected], $container->getAutoconfiguredInstanceof());
}
Expand Down Expand Up @@ -88,4 +90,21 @@ public function testMissingParent()

$this->addToAssertionCount(1);
}

public function testStaticConstructor()
{
$container = new ContainerBuilder();
$container->register('foo', StaticConstructorAutoconfigure::class)
->setAutoconfigured(true);

$argument = new BoundArgument('foo', false, BoundArgument::INSTANCEOF_BINDING, realpath(__DIR__.'/../Fixtures/StaticConstructorAutoconfigure.php'));

(new RegisterAutoconfigureAttributesPass() 10000 )->process($container);

$expected = (new ChildDefinition(''))
->setFactory([null, 'create'])
->setBindings(['$foo' => $argument])
;
$this->assertEquals([StaticConstructorAutoconfigure::class => $expected], $container->getAutoconfiguredInstanceof());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
bind: [
'$bar' => 1,
],
constructor: 'create'
)]
class AutoconfigureAttributed
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,12 @@ public function __construct($quz = null, \NonExistent $nonExistent = null, BarIn
public static function create(\NonExistent $nonExistent = null, $factory = null)
{
}

public function createNonStatic()
{
}

private static function createPrivateStatic()
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\StaticConstructor;

class PrototypeStaticConstructor implements PrototypeStaticConstructorInterface
{
public static function create(): static
{
return new self();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\StaticConstructor;

class PrototypeStaticConstructorAsArgument
{
public function __construct(private PrototypeStaticConstructor $prototypeStaticConstructor)
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\StaticConstructor;

interface PrototypeStaticConstructorInterface
{
public static function create(): static;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?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\Fixtures;

use Symfony\Component\DependencyInjection\Attribute\Autoconfigure;
use Symfony\Component\DependencyInjection\Attribute\Factory;

#[Autoconfigure(bind: ['$foo' => 'foo'], constructor: 'create')]
class StaticConstructorAutoconfigure
{
public function __construct(private readonly string $bar)
{
}

public function getBar(): string
{
return $this->bar;
}

public static function create(string $foo): static
{
return new self($foo);
}
}
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
foo:
class: Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\StaticConstructor\PrototypeStaticConstructorAsArgument
public: true
arguments: [!service { class: Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\StaticConstructor\PrototypeStaticConstructor, constructor: create }]
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\StaticConstructor\PrototypeStaticConstructor;
use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\StaticConstructor\PrototypeStaticConstructorAsArgument;

return function (ContainerConfigurator $c) {
$s = $c->services()->defaults()->public();
$s->set('foo', PrototypeStaticConstructorAsArgument::class)
->args(
[inline_service(PrototypeStaticConstructor::class)
->constructor('create')]
);
};
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
foo:
class: Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\StaticConstructor\PrototypeStaticConstructor
public: true
constructor: create
646B
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\StaticConstructor\PrototypeStaticConstructor;
use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\StaticConstructor\PrototypeStaticConstructorInterface;

return function (ContainerConfigurator $c) {
$s = $c->services()->defaults()->public();
$s->instanceof(PrototypeStaticConstructorInterface::class)
->constructor('create');

$s->set('foo', PrototypeStaticConstructor::class);
};
Loading
0