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

Skip to content

[DependencyInjection] Configure service tags via attributes #39776

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 1 commit 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
@@ -0,0 +1,47 @@
<?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\Compiler;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Contracts\Service\Attribute\TagInterface;

final class AttributeAutoconfigurationPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container): void
{
if (80000 > \PHP_VERSION_ID || !interface_exists(TagInterface::class)) {
return;
}

foreach ($container->getDefinitions() as $definition) {
if (!$definition->isAutoconfigured()) {
continue;
}

if (!$class = $container->getParameterBag()->resolveValue($definition->getClass())) {
continue;
}

try {
$reflector = new \ReflectionClass($class);
} catch (\ReflectionException $e) {
continue;
}

foreach ($reflector->getAttributes(TagInterface::class, \ReflectionAttribute::IS_INSTANCEOF) as $attribute) {
/** @var TagInterface $tag */
$tag = $attribute->newInstance();
$definition->addTag($tag->getName(), $tag->getAttributes());
}
}
}
}
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 AttributeAutoconfigurationPass(),
new ResolveInstanceofConditionalsPass(),
new RegisterEnvVarProcessorsPass(),
],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Argument\ServiceLocatorArgument;
use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\DependencyInjection\Reference;
Expand All @@ -24,6 +25,10 @@
use Symfony\Component\DependencyInjection\Tests\Fixtures\FooBarTaggedClass;
use Symfony\Component\DependencyInjection\Tests\Fixtures\FooBarTaggedForDefaultPriorityClass;
use Symfony\Component\DependencyInjection\Tests\Fixtures\FooTagClass;
use Symfony\Component\DependencyInjection\Tests\Fixtures\TaggedService1;
use Symfony\Component\DependencyInjection\Tests\Fixtures\TaggedService2;
use Symfony\Component\DependencyInjection\Tests\Fixtures\TaggedService3;
use Symfony\Contracts\Service\Attribute\TagInterface;
use Symfony\Contracts\Service\ServiceProviderInterface;
use Symfony\Contracts\Service\ServiceSubscriberInterface;

Expand Down Expand Up @@ -506,6 +511,45 @@ public function testTaggedServiceLocatorWithDefaultIndex()
];
$this->assertSame($expected, ['baz' => $serviceLocator->get('baz')]);
}

/**
* @requires PHP 8
*/
public function testTagsViaAttribute()
{
if (!\interface_exists(TagInterface::class)) {
self::markTestSkipped('This test requires symfony/service-contracts 2.4 or newer.');
}

$container = new ContainerBuilder();
$container->register('one', TaggedService1::class)
->setPublic(true)
->setAutoconfigured(true);
$container->register('two', TaggedService2::class)
->setPublic(true)
->setAutoconfigured(true);
$container->register('three', TaggedService3::class)
->setPublic(true)
->setAutoconfigured(true);

$collector = new TagCollector();
$container->addCompilerPass($collector);

$container->compile();

self::assertSame([
'one' => [
['foo' => 'bar', 'priority' => 0],
['bar' => 'baz', 'priority' => 0],
],
'two' => [
['someAttribute' => 'prio 100', 'priority' => 100],
],
'three' => [
['someAttribute' => 'custom_tag_class'],
],
], $collector->collectedTags);
}
}

class ServiceSubscriberStub implements ServiceSubscriberInterface
Expand Down Expand Up @@ -566,3 +610,13 @@ public function setSunshine($type)
{
}
}

final class TagCollector implements CompilerPassInterface
{
public $collectedTags;

public function process(ContainerBuilder $container): void
{
$this->collectedTags = $container->findTaggedServiceIds('app.custom_tag');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?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\Tests\Fixtures\Attribute;

use Symfony\Contracts\Service\Attribute\TagInterface;

#[\Attribute(\Attribute::TARGET_CLASS)]
final class CustomTag implements TagInterface
{
public function getName(): string
{
return 'app.custom_tag';
}

public function getAttributes(): array
{
return ['someAttribute' => 'custom_tag_class'];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?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\Tests\Fixtures;

use Symfony\Contracts\Service\Attribute\Tag;

#[Tag(name: 'app.custom_tag', attributes: ['foo' => 'bar'])]
#[Tag(name: 'app.custom_tag', attributes: ['bar' => 'baz'])]
final class TaggedService1
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?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\Tests\Fixtures;

use Symfony\Contracts\Service\Attribute\Tag;

#[Tag(name: 'app.custom_tag', priority: 100, attributes: ['someAttribute' => 'prio 100'])]
final class TaggedService2
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?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\Tests\Fixtures;

use Symfony\Component\DependencyInjection\Tests\Fixtures\Attribute\CustomTag;

#[CustomTag]
final class TaggedService3
{
}
44 changes: 44 additions & 0 deletions src/Symfony/Component/EventDispatcher/Attribute/EventListener.php
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 <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\EventDispatcher\Attribute;

use Symfony\Contracts\Service\Attribute\TagInterface;

/**
* Service tag to autoconfigure event listeners.
*
* @author Alexander M. Turek <[email protected]>
*/
#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::IS_REPEATABLE)]
class EventListener implements TagInterface
{
public function __construct(
private ?string $event = null,
private ?string $method = null,
private int $priority = 0
) {
}

public function getName(): string
{
return 'kernel.event_listener';
}

public function getAttributes(): array
{
return [
'event' => $this->event,
'method' => $this->method,
'priority' => $this->priority,
];
}
}
5 changes: 5 additions & 0 deletions src/Symfony/Component/EventDispatcher/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

5.3.0
-----

* Added the `EventListener` service tag attribute for PHP 8.

5.1.0
-----

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,17 @@

use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
use Symfony\Component\DependencyInjection\Compiler\AttributeAutoconfigurationPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\EventDispatcher\DependencyInjection\AddEventAliasesPass;
use Symfony\Component\EventDispatcher\DependencyInjection\RegisterListenersPass;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\Tests\Fixtures\CustomEvent;
use Symfony\Component\EventDispatcher\Tests\Fixtures\TaggedInvokableListener;
use Symfony\Component\EventDispatcher\Tests\Fixtures\TaggedMultiListener;
use Symfony\Contracts\Service\Attribute\TagInterface;

class RegisterListenersPassTest extends TestCase
{
Expand Down Expand Up @@ -231,6 +236,82 @@ public function testInvokableEventListener()
$this->assertEquals($expectedCalls, $definition->getMethodCalls());
}

/**
* @requires PHP 8
*/
public function testTaggedInvokableEventListener()
{
if (!\interface_exists(TagInterface::class)) {
self::markTestSkipped('This test requires symfony/service-contracts 2.4 or newer.');
}

$container = new ContainerBuilder();
$container->register('foo', TaggedInvokableListener::class)->setAutoconfigured(true);
$container->register('event_dispatcher', \stdClass::class);

(new AttributeAutoconfigurationPass())->process($container);
(new RegisterListenersPass())->process($container);

$definition = $container->getDefinition('event_dispatcher');
$expectedCalls = [
[
'addListener',
[
CustomEvent::class,
[new ServiceClosureArgument(new Reference('foo')), '__invoke'],
0,
],
],
];
$this->assertEquals($expectedCalls, $definition->getMethodCalls());
}

/**
* @requires PHP 8
*/
public function testTaggedMultiEventListener()
{
if (!\interface_exists(TagInterface::class)) {
self::markTestSkipped('This test requires symfony/service-contracts 2.4 or newer.');
}

$container = new ContainerBuilder();
$container->register('foo', TaggedMultiListener::class)->setAutoconfigured(true);
$container->register('event_dispatcher', \stdClass::class);

(new AttributeAutoconfigurationPass())->process($container);
(new RegisterListenersPass())->process($container);

$definition = $container->getDefinition('event_dispatcher');
$expectedCalls = [
[
'addListener',
[
CustomEvent::class,
[new ServiceClosureArgument(new Reference('foo')), 'onCustomEvent'],
0,
],
],
[
'addListener',
[
'foo',
[new ServiceClosureArgument(new Reference('foo')), 'onFoo'],
42,
],
],
[
'addListener',
[
'bar',
[new ServiceClosureArgument(new Reference('foo')), 'onBarEvent'],
0,
],
],
];
$this->assertEquals($expectedCalls, $definition->getMethodCalls());
}

public function testAliasedEventListener()
{
$container = new ContainerBuilder();
Expand Down Expand Up @@ -416,10 +497,6 @@ final class AliasedEvent
{
}

final class CustomEvent
{
}

final class TypedListener
{
public function __invoke(AliasedEvent $event): void
Expand Down
Loading