Skip to content

[DependencyInjection] Add #[Autoconfigure] to help define autoconfiguration rules #39804

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
Feb 16, 2021
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,34 @@
<?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\Attribute;

/**
* An attribute to tell how a base type should be autoconfigured.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::IS_REPEATABLE)]
class Autoconfigure
{
public function __construct(
public ?array $tags = null,
public ?array $calls = null,
public ?array $bind = null,
public bool|string|null $lazy = null,
public ?bool $public = null,
public ?bool $shared = null,
public ?bool $autowire = null,
public ?array $properties = null,
public array|string|null $configurator = null,
) {
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?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\Attribute;

/**
* An attribute to tell how a base type should be tagged.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::IS_REPEATABLE)]
class AutoconfigureTag extends Autoconfigure
{
public function __construct(string $name = null, array $attributes = [])
{
parent::__construct(
tags: [
[$name ?? 0 => $attributes],
]
);
}
}
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

* Add `ServicesConfigurator::remove()` in the PHP-DSL
* Add `%env(not:...)%` processor to negate boolean values
* Add support for loading autoconfiguration rules via the `#[Autoconfigure]` and `#[AutoconfigureTag]` attributes on PHP 8

5.2.0
-----
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ public function __construct()
$this->beforeOptimizationPasses = [
100 => [
new ResolveClassPass(),
new RegisterAutoconfigureAttributesPass(),
new ResolveInstanceofConditionalsPass(),
new RegisterEnvVarProcessorsPass(),
],
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<?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\Compiler;

use Symfony\Component\DependencyInjection\Attribute\Autoconfigure;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;

/**
* Reads #[Autoconfigure] attributes on definitions that are autoconfigured
* and don't have the "container.ignore_attributes" tag.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
final class RegisterAutoconfigureAttributesPass implements CompilerPassInterface
{
private $ignoreAttributesTag;
private $registerForAutoconfiguration;

public function __construct(string $ignoreAttributesTag = 'container.ignore_attributes')
{
if (80000 > \PHP_VERSION_ID) {
return;
}

$this->ignoreAttributesTag = $ignoreAttributesTag;

$parseDefinitions = new \ReflectionMethod(YamlFileLoader::class, 'parseDefinitions');
$parseDefinitions->setAccessible(true);
$yamlLoader = $parseDefinitions->getDeclaringClass()->newInstanceWithoutConstructor();

$this->registerForAutoconfiguration = static function (ContainerBuilder $container, \ReflectionClass $class, \ReflectionAttribute $attribute) use ($parseDefinitions, $yamlLoader) {
$attribute = (array) $attribute->newInstance();

foreach ($attribute['tags'] ?? [] as $i => $tag) {
if (\is_array($tag) && [0] === array_keys($tag)) {
$attribute['tags'][$i] = [$class->name => $tag[0]];
}
}

$parseDefinitions->invoke(
$yamlLoader,
[
'services' => [
'_instanceof' => [
$class->name => [$container->registerForAutoconfiguration($class->name)] + $attribute,
],
],
],
$class->getFileName()
);
};
}

/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
{
if (80000 > \PHP_VERSION_ID) {
return;
}

foreach ($container->getDefinitions() as $id => $definition) {
if ($this->accept($definition) && null !== $class = $container->getReflectionClass($definition->getClass())) {
$this->processClass($container, $class);
}
}
}

public function accept(Definition $definition): bool
{
return 80000 <= \PHP_VERSION_ID && $definition->isAutoconfigured() && !$definition->hasTag($this->ignoreAttributesTag);
}

public function processClass(ContainerBuilder $container, \ReflectionClass $class)
{
foreach ($class->getAttributes(Autoconfigure::class, \ReflectionAttribute::IS_INSTANCEOF) as $attribute) {
($this->registerForAutoconfiguration)($container, $class, $attribute);
}
}
}
10 changes: 8 additions & 2 deletions src/Symfony/Component/DependencyInjection/Loader/FileLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use Symfony\Component\Config\Loader\Loader;
use Symfony\Component\Config\Resource\GlobResource;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\Compiler\RegisterAutoconfigureAttributesPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
Expand Down Expand Up @@ -96,7 +97,8 @@ public function registerClasses(Definition $prototype, string $namespace, string
throw new InvalidArgumentException(sprintf('Namespace is not a valid PSR-4 prefix: "%s".', $namespace));
}

$classes = $this->findClasses($namespace, $resource, (array) $exclude);
$autoconfigureAttributes = new RegisterAutoconfigureAttributesPass();
$classes = $this->findClasses($namespace, $resource, (array) $exclude, $autoconfigureAttributes->accept($prototype) ? $autoconfigureAttributes : null);
// prepare for deep cloning
$serializedPrototype = serialize($prototype);

Expand Down Expand Up @@ -149,7 +151,7 @@ protected function setDefinition(string $id, Definition $definition)
}
}

private function findClasses(string $namespace, string $pattern, array $excludePatterns): array
private function findClasses(string $namespace, string $pattern, array $excludePatterns, ?RegisterAutoconfigureAttributesPass $autoconfigureAttributes): array
{
$parameterBag = $this->container->getParameterBag();

Expand Down Expand Up @@ -207,6 +209,10 @@ private function findClasses(string $namespace, string $pattern, array $excludeP
if ($r->isInstantiable() || $r->isInterface()) {
$classes[$class] = null;
}

if ($autoconfigureAttributes && !$r->isInstantiable()) {
$autoconfigureAttributes->processClass($this->container, $r);
}
}

// track only for new & removed files
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,9 @@ private function parseDefinition(string $id, $service, string $file, array $defa
];
}

$definition = isset($service[0]) && $service[0] instanceof Definition ? array_shift($service) : null;
$return = null === $definition ? $return : true;

$this->checkDefinition($id, $service, $file);

if (isset($service['alias'])) {
Expand Down Expand Up @@ -423,7 +426,9 @@ private function parseDefinition(string $id, $service, string $file, array $defa
return $return ? $alias : $this->container->setAlias($id, $alias);
}

if ($this->isLoadingInstanceof) {
if (null !== $definition) {
// no-op
} elseif ($this->isLoadingInstanceof) {
$definition = new ChildDefinition('');
} elseif (isset($service['parent'])) {
if ('' !== $service['parent'] && '@' === $service['parent'][0]) {
Expand Down Expand Up @@ -627,7 +632,8 @@ private function parseDefinition(string $id, $service, string $file, array $defa

if (isset($defaults['bind']) || isset($service['bind'])) {
// deep clone, to avoid multiple process of the same instance in the passes
$bindings = isset($defaults['bind']) ? unserialize(serialize($defaults['bind'])) : [];
$bindings = $definition->getBindings();
$bindings += isset($defaults['bind']) ? unserialize(serialize($defaults['bind'])) : [];

if (isset($service['bind'])) {
if (!\is_array($service['bind'])) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?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\Compiler;

use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Argument\BoundArgument;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\Compiler\RegisterAutoconfigureAttributesPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Tests\Fixtures\AutoconfigureAttributed;
use Symfony\Component\DependencyInjection\Tests\Fixtures\AutoconfiguredInterface;

/**
* @requires PHP 8
*/
class RegisterAutoconfigureAttributesPassTest extends TestCase
{
public function testProcess()
{
$container = new ContainerBuilder();
$container->register('foo', AutoconfigureAttributed::class)
->setAutoconfigured(true);

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

$argument = new BoundArgument(1, true, BoundArgument::INSTANCEOF_BINDING, realpath(__DIR__.'/../Fixtures/AutoconfigureAttributed.php'));
$values = $argument->getValues();
--$values[1];
$argument->setValues($values);

$expected = (new ChildDefinition(''))
->setLazy(true)
->setPublic(true)
->setAutowired(true)
->setShared(true)
->setProperties(['bar' => 'baz'])
->setConfigurator(new Reference('bla'))
->addTag('a_tag')
->addTag('another_tag', ['attr' => 234])
->addMethodCall('setBar', [2, 3])
->setBindings(['$bar' => $argument])
;
$this->assertEquals([AutoconfigureAttributed::class => $expected], $container->getAutoconfiguredInstanceof());
}

public function testIgnoreAttribute()
{
$container = new ContainerBuilder();
$container->register('foo', AutoconfigureAttributed::class)
->addTag('container.ignore_attributes')
->setAutoconfigured(true);

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

$this->assertSame([], $container->getAutoconfiguredInstanceof());
}

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

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

$expected = (new ChildDefinition(''))
->addTag(AutoconfiguredInterface::class, ['foo' => 123])
;
$this->assertEquals([AutoconfiguredInterface::class => $expected], $container->getAutoconfiguredInstanceof());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace Symfony\Component\DependencyInjection\Tests\Fixtures;

use Symfony\Component\DependencyInjection\Attribute\Autoconfigure;

#[Autoconfigure(
lazy: true,
public: true,
autowire: true,
shared: true,
properties: [
'bar' => 'baz',
],
configurator: '@bla',
tags: [
'a_tag',
['another_tag' => ['attr' => 234]],
],
calls: [
['setBar' => [2, 3]]
],
bind: [
'$bar' => 1,
],
)]
class AutoconfigureAttributed
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace Symfony\Component\DependencyInjection\Tests\Fixtures;

use Symfony\Component\DependencyInjection\Attribute\AutoconfigureTag;

#[AutoconfigureTag(attributes: ['foo' => 123])]
interface AutoconfiguredInterface
{
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

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

use Symfony\Component\DependencyInjection\Attribute\Autoconfigure;

#[Autoconfigure(tags: ['foo'])]
interface FooInterface
{
}
Loading