Skip to content

[DependencyInjection] Add AsAlias attribute #41207

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

Closed
wants to merge 2 commits into from
Closed
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 @@ -45,6 +45,7 @@
use Symfony\Component\Console\Command\Command;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
use Symfony\Component\DependencyInjection\Attribute\AsAlias;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
Expand Down Expand Up @@ -555,6 +556,20 @@ public function load(array $configs, ContainerBuilder $container)
$container->registerAttributeForAutoconfiguration(AsController::class, static function (ChildDefinition $definition, AsController $attribute): void {
$definition->addTag('controller.service_arguments');
});
$container->registerAttributeForAutoconfiguration(AsAlias::class, static function (ChildDefinition $definition, AsAlias $attribute, \ReflectionClass $class, string $serviceId, ContainerBuilder $container): void {
static $usedAttributeAliases = [];

$containerHasAlias = $container->hasAlias($alias = $attribute->id);

// Ignores the attributes if there is already an alias
// or if there are two competing attributes
if (!$containerHasAlias && !isset($usedAttributeAliases[$alias])) {
$usedAttributeAliases[$alias] = true;
$container->setAlias($alias, new Alias($serviceId, $attribute->public));
} elseif ($containerHasAlias && isset($usedAttributeAliases[$alias])) {
$container->removeAlias($alias);
}
});

if (!$container->getParameter('kernel.debug')) {
// remove tagged iterator argument for resource checkers
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?php

namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Fixtures;

interface FooInterface
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Fixtures;

use Symfony\Component\DependencyInjection\Attribute\AsAlias;

#[AsAlias(id: FooInterface::class)]
class WithAsAlias
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Fixtures;

use Symfony\Component\DependencyInjection\Attribute\AsAlias;

#[AsAlias(id: FooInterface::class)]
class WithAsAliasDuplicate
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Fixtures;

use Symfony\Component\DependencyInjection\Attribute\AsAlias;

#[AsAlias(id: FooInterface::class, public: true)]
#[AsAlias(id: 'some-alias')]
class WithAsAliasMultiple
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Fixtures;

use Symfony\Component\DependencyInjection\Attribute\AsAlias;

#[AsAlias(id: 'some-alias', public: true)]
class WithAsAliasPublic
{
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@
use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddAnnotationsCachedReaderPass;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\FrameworkExtension;
use Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Fixtures\FooInterface;
use Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Fixtures\WithAsAlias;
use Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Fixtures\WithAsAliasDuplicate;
use Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Fixtures\WithAsAliasMultiple;
use Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Fixtures\WithAsAliasPublic;
use Symfony\Bundle\FrameworkBundle\Tests\Fixtures\Messenger\DummyMessage;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Bundle\FullStack;
Expand All @@ -35,6 +40,7 @@
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\Compiler\AttributeAutoconfigurationPass;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\ResolveInstanceofConditionalsPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
Expand Down Expand Up @@ -1884,6 +1890,88 @@ public function testIfNotifierTransportsAreKnownByFrameworkExtension()
}
}

/**
* @requires PHP 8
*
* @dataProvider provideClassesWithAsAliasAttributes
*/
public function testAsAliasAttributesAreResolved(string $class, array $expectedAliases)
{
$container = $this->createContainer(['kernel.charset' => 'UTF-8']);
$container->getCompilerPassConfig()->setBeforeOptimizationPasses([new AttributeAutoconfigurationPass()]);
$container->getCompilerPassConfig()->setOptimizationPasses([]);
$container->getCompilerPassConfig()->setRemovingPasses([]);
$container->getCompilerPassConfig()->setAfterRemovingPasses([]);

$container->registerExtension(new FrameworkExtension());
$container->loadFromExtension('framework');

$container->register($class, $class)->setAutoconfigured(true);

$container->compile();

foreach ($expectedAliases as $expectedAlias) {
$this->assertTrue($container->hasAlias($expectedAlias['id']));
$this->assertSame($expectedAlias['public'], $container->getAlias($expectedAlias['id'])->isPublic());
}
}

public function provideClassesWithAsAliasAttributes(): iterable
{
yield 'Private' => [WithAsAlias::class, [['id' => FooInterface::class, 'public' => false]]];
yield 'Public' => [WithAsAliasPublic::class, [['id' => 'some-alias', 'public' => true]]];
yield 'Multiple' => [WithAsAliasMultiple::class, [
['id' => FooInterface::class, 'public' => true],
['id' => 'some-alias', 'public' => false],
]];
}

/**
* @requires PHP 8
*/
public function testAsAliasAttributesAreIgnoredWhenAliasExists()
{
$container = $this->createContainer(['kernel.charset' => 'UTF-8']);
$container->getCompilerPassConfig()->setBeforeOptimizationPasses([new AttributeAutoconfigurationPass()]);
$container->getCompilerPassConfig()->setOptimizationPasses([]);
$container->getCompilerPassConfig()->setRemovingPasses([]);
$container->getCompilerPassConfig()->setAfterRemovingPasses([]);

$container->registerExtension(new FrameworkExtension());
$container->loadFromExtension('framework');

$container->setAlias(FooInterface::class, WithAsAliasPublic::class);
$container->register(WithAsAlias::class, WithAsAlias::class)->setAutoconfigured(true);

$container->compile();

$this->assertTrue($container->hasAlias(FooInterface::class));
$this->assertSame(WithAsAliasPublic::class, (string) $container->getAlias(FooInterface::class));
}

/**
* @requires PHP 8
*/
public function testAsAliasAttributesAreIgnoredWhenMultipleAttributesExist()
{
$container = $this->createContainer(['kernel.charset' => 'UTF-8']);
$container->getCompilerPassConfig()->setBeforeOptimizationPasses([new AttributeAutoconfigurationPass()]);
$container->getCompilerPassConfig()->setOptimizationPasses([]);
$container->getCompilerPassConfig()->setRemovingPasses([]);
$container->getCompilerPassConfig()->setAfterRemovingPasses([]);

$container->registerExtension(new FrameworkExtension());
$container->loadFromExtension('framework');

$container->register(WithAsAlias::class, WithAsAlias::class)->setAutoconfigured(true);
$container->register(WithAsAliasDuplicate::class, WithAsAliasDuplicate::class)->setAutoconfigured(true);
$container->register(WithAsAliasMultiple::class, WithAsAliasMultiple::class)->setAutoconfigured(true);

$container->compile();

$this->assertFalse($container->hasAlias(FooInterface::class));
}

protected function createContainer(array $data = [])
{
return new ContainerBuilder(new EnvPlaceholderParameterBag(array_merge([
Expand Down
25 changes: 25 additions & 0 deletions src/Symfony/Component/DependencyInjection/Attribute/AsAlias.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?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 under which alias a service should be registered.
*/
#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::IS_REPEATABLE)]
class AsAlias
{
public function __construct(
public string $id,
public bool $public = false,
) {
}
}
1 change: 1 addition & 0 deletions src/Symfony/Component/DependencyInjection/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ CHANGELOG
* Add support for `ConfigBuilder` in the `PhpFileLoader`
* Add `ContainerConfigurator::env()` to get the current environment
* Add `#[Target]` to tell how a dependency is used and hint named autowiring aliases
* Add `#[AsAlias]` to tell under which alias a service should be registered

5.2.0
-----
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ protected function processValue($value, bool $isRoot = false)
$conditionals = $instanceof[$reflector->getName()] ?? new ChildDefinition('');
foreach ($reflector->getAttributes() as $attribute) {
if ($configurator = $autoconfiguredAttributes[$attribute->getName()] ?? null) {
$configurator($conditionals, $attribute->newInstance(), $reflector);
$configurator($conditionals, $attribute->newInstance(), $reflector, $this->currentId, $this->container);
}
}
if (!isset($instanceof[$reflector->getName()]) && new ChildDefinition('') != $conditionals) {
Expand Down