Skip to content

Commit ac2f062

Browse files
ruudknicolas-grekas
authored andcommitted
[DependencyInjection] Autoconfigurable attributes on methods, properties and parameters
1 parent e442d4a commit ac2f062

File tree

4 files changed

+30
-4
lines changed

4 files changed

+30
-4
lines changed

Attribute/AsEventListener.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
*
1717
* @author Alexander M. Turek <[email protected]>
1818
*/
19-
#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::IS_REPEATABLE)]
19+
#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
2020
class AsEventListener
2121
{
2222
public function __construct(

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
CHANGELOG
22
=========
33

4+
5.4
5+
---
6+
7+
* Allow `#[AsEventListener]` attribute on methods
8+
49
5.3
510
---
611

Tests/DependencyInjection/RegisterListenersPassTest.php

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -291,9 +291,17 @@ public function testTaggedMultiEventListener()
291291
}
292292

293293
$container = new ContainerBuilder();
294-
$container->registerAttributeForAutoconfiguration(AsEventListener::class, static function (ChildDefinition $definition, AsEventListener $attribute): void {
295-
$definition->addTag('kernel.event_listener', get_object_vars($attribute));
296-
});
294+
$container->registerAttributeForAutoconfiguration(AsEventListener::class, eval(<<<'PHP'
295+
return static function (\Symfony\Component\DependencyInjection\ChildDefinition $definition, \Symfony\Component\EventDispatcher\Attribute\AsEventListener $attribute, \ReflectionClass|\ReflectionMethod $reflector): void {
296+
$tagAttributes = get_object_vars($attribute);
297+
if ($reflector instanceof \ReflectionMethod) {
298+
$tagAttributes['method'] = $reflector->getName();
299+
}
300+
$definition->addTag('kernel.event_listener', $tagAttributes);
301+
};
302+
PHP
303+
));
304+
297305
$container->register('foo', TaggedMultiListener::class)->setAutoconfigured(true);
298306
$container->register('event_dispatcher', \stdClass::class);
299307

@@ -327,6 +335,14 @@ public function testTaggedMultiEventListener()
327335
0,
328336
],
329337
],
338+
[
339+
'addListener',
340+
[
341+
'baz',
342+
[new ServiceClosureArgument(new Reference('foo')), 'onBazEvent'],
343+
0,
344+
],
345+
],
330346
];
331347
$this->assertEquals($expectedCalls, $definition->getMethodCalls());
332348
}

Tests/Fixtures/TaggedMultiListener.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,9 @@ public function onFoo(): void
2929
public function onBarEvent(): void
3030
{
3131
}
32+
33+
#[AsEventListener(event: 'baz')]
34+
public function onBazEvent(): void
35+
{
36+
}
3237
}

0 commit comments

Comments
 (0)