Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[DependencyInjection] Add AsAlias attribute #49411

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 18, 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
27 changes: 27 additions & 0 deletions src/Symfony/Component/DependencyInjection/Attribute/AsAlias.php
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 <[email protected]>
*
* 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 or to use the implemented interface if no parameter is given.
*
* @author Alan Poulain <[email protected]>
*/
#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::IS_REPEATABLE)]
final class AsAlias
{
public function __construct(
public ?string $id = null,
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 @@ -11,6 +11,7 @@ CHANGELOG
* Deprecate undefined and numeric keys with `service_locator` config
* Fail if Target attribute does not exist during compilation
* Enable deprecating parameters with `ContainerBuilder::deprecateParameter()`
* Add `#[AsAlias]` attribute to tell under which alias a service should be registered or to use the implemented interface if no parameter is given

6.2
---
Expand Down
34 changes: 32 additions & 2 deletions src/Symfony/Component/DependencyInjection/Loader/FileLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,15 @@
use Symfony\Component\Config\Loader\FileLoader as BaseFileLoader;
use Symfony\Component\Config\Loader\Loader;
use Symfony\Component\Config\Resource\GlobResource;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Attribute\AsAlias;
use Symfony\Component\DependencyInjection\Attribute\When;
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;
use Symfony\Component\DependencyInjection\Exception\LogicException;

/**
* FileLoader is the abstract class used by all built-in loaders that are file based.
Expand All @@ -38,6 +41,8 @@ abstract class FileLoader extends BaseFileLoader
protected $instanceof = [];
protected $interfaces = [];
protected $singlyImplemented = [];
/** @var array<string, Alias> */
protected $aliases = [];
protected $autoRegisterAliasesForSinglyImplementedInterfaces = true;

public function __construct(ContainerBuilder $container, FileLocatorInterface $locator, string $env = null)
Expand Down Expand Up @@ -140,12 +145,37 @@ public function registerClasses(Definition $prototype, string $namespace, string

continue;
}
$interfaces = [];
foreach (class_implements($class, false) as $interface) {
$this->singlyImplemented[$interface] = ($this->singlyImplemented[$interface] ?? $class) !== $class ? false : $class;
$interfaces[] = $interface;
}

if (!$autoconfigureAttributes) {
continue;
}
$r = $this->container->getReflectionClass($class);
$defaultAlias = 1 === \count($interfaces) ? $interfaces[0] : null;
foreach ($r->getAttributes(AsAlias::class) as $attr) {
/** @var AsAlias $attribute */
$attribute = $attr->newInstance();
$alias = $attribute->id ?? $defaultAlias;
$public = $attribute->public;
if (null === $alias) {
throw new LogicException(sprintf('Alias cannot be automatically determined for class "%s". If you have used the #[AsAlias] attribute with a class implementing multiple interfaces, add the interface you want to alias to the first parameter of #[AsAlias].', $class));
}
if (isset($this->aliases[$alias])) {
throw new LogicException(sprintf('The "%s" alias has already been defined with the #[AsAlias] attribute in "%s".', $alias, $this->aliases[$alias]));
}
$this->aliases[$alias] = new Alias($class, $public);
}
}
}

foreach ($this->aliases as $alias => $aliasDefinition) {
$this->container->setAlias($alias, $aliasDefinition);
}

if ($this->autoRegisterAliasesForSinglyImplementedInterfaces) {
$this->registerAliasesForSinglyImplementedInterfaces();
}
Expand All @@ -157,12 +187,12 @@ public function registerClasses(Definition $prototype, string $namespace, string
public function registerAliasesForSinglyImplementedInterfaces()
{
foreach ($this->interfaces as $interface) {
if (!empty($this->singlyImplemented[$interface]) && !$this->container->has($interface)) {
if (!empty($this->singlyImplemented[$interface]) && !isset($this->aliases[$interface]) && !$this->container->has($interface)) {
$this->container->setAlias($interface, $this->singlyImplemented[$interface]);
}
}

$this->interfaces = $this->singlyImplemented = [];
$this->interfaces = $this->singlyImplemented = $this->aliases = [];
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?php

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

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

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

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

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

use Symfony\Component\DependencyInjection\Attribute\AsAlias;

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

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

use Symfony\Component\DependencyInjection\Attribute\AsAlias;

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

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

use Symfony\Component\DependencyInjection\Attribute\AsAlias;

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

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

use Symfony\Component\DependencyInjection\Attribute\AsAlias;

#[AsAlias]
class WithAsAliasInterface implements AliasFooInterface
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

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

use Symfony\Component\DependencyInjection\Attribute\AsAlias;

#[AsAlias(id: AliasFooInterface::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\Component\DependencyInjection\Tests\Fixtures\PrototypeAsAlias;

use Symfony\Component\DependencyInjection\Attribute\AsAlias;

#[AsAlias]
class WithAsAliasMultipleInterface implements AliasFooInterface, AliasBarInterface
{
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@
use PHPUnit\Framework\TestCase;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Config\Loader\LoaderResolver;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Loader\FileLoader;
use Symfony\Component\DependencyInjection\Loader\IniFileLoader;
use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
Expand All @@ -32,6 +34,12 @@
use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\OtherDir\Baz;
use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Sub\Bar;
use Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\Sub\BarInterface;
use Symfony\Component\DependencyInjection\Tests\Fixtures\PrototypeAsAlias\AliasBarInterface;
use Symfony\Component\DependencyInjection\Tests\Fixtures\PrototypeAsAlias\AliasFooInterface;
use Symfony\Component\DependencyInjection\Tests\Fixtures\PrototypeAsAlias\WithAsAlias;
use Symfony\Component\DependencyInjection\Tests\Fixtures\PrototypeAsAlias\WithAsAliasIdMultipleInterface;
use Symfony\Component\DependencyInjection\Tests\Fixtures\PrototypeAsAlias\WithAsAliasInterface;
use Symfony\Component\DependencyInjection\Tests\Fixtures\PrototypeAsAlias\WithAsAliasMultiple;

class FileLoaderTest extends TestCase
{
Expand Down Expand Up @@ -274,6 +282,73 @@ public function testRegisterClassesWithWhenEnv(?string $env, bool $expected)

$this->assertSame($expected, $container->has(Foo::class));
}

/**
* @dataProvider provideResourcesWithAsAliasAttributes
*/
public function testRegisterClassesWithAsAlias(string $resource, array $expectedAliases)
{
$container = new ContainerBuilder();
$loader = new TestFileLoader($container, new FileLocator(self::$fixturesPath.'/Fixtures'));
$loader->registerClasses(
(new Definition())->setAutoconfigured(true),
'Symfony\Component\DependencyInjection\Tests\Fixtures\PrototypeAsAlias\\',
$resource
);

$this->assertEquals($expectedAliases, $container->getAliases());
}

public static function provideResourcesWithAsAliasAttributes(): iterable
{
yield 'Private' => ['PrototypeAsAlias/{WithAsAlias,AliasFooInterface}.php', [AliasFooInterface::class => new Alias(WithAsAlias::class)]];
yield 'Interface' => ['PrototypeAsAlias/{WithAsAliasInterface,AliasFooInterface}.php', [AliasFooInterface::class => new Alias(WithAsAliasInterface::class)]];
yield 'Multiple' => ['PrototypeAsAlias/{WithAsAliasMultiple,AliasFooInterface}.php', [
AliasFooInterface::class => new Alias(WithAsAliasMultiple::class, true),
'some-alias' => new Alias(WithAsAliasMultiple::class),
]];
yield 'Multiple with id' => ['PrototypeAsAlias/{WithAsAliasIdMultipleInterface,AliasBarInterface,AliasFooInterface}.php', [
AliasBarInterface::class => new Alias(WithAsAliasIdMultipleInterface::class),
AliasFooInterface::class => new Alias(WithAsAliasIdMultipleInterface::class),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is the AliasFooInterface being registered? Is it because of the WithAsAliasIdMultipleInterface class being the only one implementing this interface?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. I think it's the right behavior, don't you think so? The other possibility would be to prevent the singly implemented interface registration if there is an AsAlias attribute on the class.

]];
}

/**
* @dataProvider provideResourcesWithDuplicatedAsAliasAttributes
*/
public function testRegisterClassesWithDuplicatedAsAlias(string $resource, string $expectedExceptionMessage)
{
$this->expectException(LogicException::class);
$this->expectExceptionMessage($expectedExceptionMessage);

$container = new ContainerBuilder();
$loader = new TestFileLoader($container, new FileLocator(self::$fixturesPath.'/Fixtures'));
$loader->registerClasses(
(new Definition())->setAutoconfigured(true),
'Symfony\Component\DependencyInjection\Tests\Fixtures\PrototypeAsAlias\\',
$resource
);
}

public static function provideResourcesWithDuplicatedAsAliasAttributes(): iterable
{
yield 'Duplicated' => ['PrototypeAsAlias/{WithAsAlias,WithAsAliasDuplicate,AliasFooInterface}.php', 'The "Symfony\Component\DependencyInjection\Tests\Fixtures\PrototypeAsAlias\AliasFooInterface" alias has already been defined with the #[AsAlias] attribute in "Symfony\Component\DependencyInjection\Tests\Fixtures\PrototypeAsAlias\WithAsAlias".'];
yield 'Interface duplicated' => ['PrototypeAsAlias/{WithAsAliasInterface,WithAsAlias,AliasFooInterface}.php', 'The "Symfony\Component\DependencyInjection\Tests\Fixtures\PrototypeAsAlias\AliasFooInterface" alias has already been defined with the #[AsAlias] attribute in "Symfony\Component\DependencyInjection\Tests\Fixtures\PrototypeAsAlias\WithAsAlias".'];
}

public function testRegisterClassesWithAsAliasAndImplementingMultipleInterfaces()
{
$this->expectException(LogicException::class);
$this->expectExceptionMessage('Alias cannot be automatically determined for class "Symfony\Component\DependencyInjection\Tests\Fixtures\PrototypeAsAlias\WithAsAliasMultipleInterface". If you have used the #[AsAlias] attribute with a class implementing multiple interfaces, add the interface you want to alias to the first parameter of #[AsAlias].');

$container = new ContainerBuilder();
$loader = new TestFileLoader($container, new FileLocator(self::$fixturesPath.'/Fixtures'));
$loader->registerClasses(
(new Definition())->setAutoconfigured(true),
'Symfony\Component\DependencyInjection\Tests\Fixtures\PrototypeAsAlias\\',
'PrototypeAsAlias/{WithAsAliasMultipleInterface,AliasBarInterface,AliasFooInterface}.php'
);
}
}

class TestFileLoader extends FileLoader
Expand Down