8000 [EventDispatcher][DX] Autoconfigure event listeners by jderusse · Pull Request #30760 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[EventDispatcher][DX] Autoconfigure event listeners #30760

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
Expand Up @@ -116,6 +116,7 @@
use Symfony\Component\Yaml\Command\LintCommand as BaseYamlLintCommand;
use Symfony\Component\Yaml\Yaml;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\EventDispatcher\EventListenerInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\Service\ResetInterface;
use Symfony\Contracts\Service\ServiceSubscriberInterface;
Expand Down Expand Up @@ -368,6 +369,8 @@ public function load(array $configs, ContainerBuilder $container)
->addTag('kernel.cache_clearer');
$container->registerForAutoconfiguration(CacheWarmerInterface::class)
->addTag('kernel.cache_warmer');
$container->registerForAutoconfiguration(EventListenerInterface::class)
->addTag('kernel.event_listener');
$container->registerForAutoconfiguration(EventSubscriberInterface::class)
->addTag('kernel.event_subscriber');
$container->registerForAutoconfiguration(ResetInterface::class)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Contracts\EventDispatcher\EventListenerInterface;

/**
* Compiler pass to register tagged services for an event dispatcher.
Expand Down Expand Up @@ -63,22 +65,41 @@ public function process(ContainerBuilder $container)
$definition = $container->findDefinition($this->dispatcherService);

foreach ($container->findTaggedServiceIds($this->listenerTag, true) as $id => $events) {
$reflection = null;
foreach ($events as $event) {
$priority = isset($event['priority']) ? $event['priority'] : 0;

if (!isset($event['event'])) {
throw new InvalidArgumentException(sprintf('Service "%s" must define the "event" attribute on "%s" tags.', $id, $this->listenerTag));
if (null === $reflection) {
$class = $container->getDefinition($id)->getClass();
if (!$reflection = $container->getReflectionClass($class)) {
throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id));
}
}
if (!$reflection->implementsInterface(EventListenerInterface::class)) {
throw new InvalidArgumentException(sprintf('Service "%s" must define the "event" attribute on "%s" tags or implements the "%s" interface.', $id, $this->listenerTag, EventListenerInterface::class));
}

$event['event'] = $this->guessListenedClass($reflection, $id);
$event['method'] = '__invoke';
} else {
$event['event'] = $aliases[$event['event']] ?? $event['event'];
}
$event['event'] = $aliases[$event['event']] ?? $event['event'];

if (!isset($event['method'])) {
$event['method'] = 'on'.preg_replace_callback([
'/(?<=\b)[a-z]/i',
'/[^a-z0-9]/i',
], function ($matches) { return strtoupper($matches[0]); }, $event['event']);
], function ($matches) { return strtoupper($matches[0]); }, (false === $p = strrpos($event['event'], '\\')) ? $event['event'] : substr($event['event'], $p + 1));
$event['method'] = preg_replace('/[^a-z0-9]/i', '', $event['method']);

if (null !== ($class = $container->getDefinition($id)->getClass()) && ($r = $container->getReflectionClass($class, false)) && !$r->hasMethod($event['method']) && $r->hasMethod('__invoke')) {
if (null === $reflection) {
$class = $container->getDefinition($id)->getClass();
if (!$reflection = $container->getReflectionC 10000 lass($class)) {
throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id));
}
}
if (!$reflection->hasMethod($event['method']) && $reflection->hasMethod('__invoke')) {
$event['method'] = '__invoke';
}
}
Expand Down Expand Up @@ -122,6 +143,40 @@ public function process(ContainerBuilder $container)
ExtractingEventDispatcher::$aliases = [];
}
}

private function guessListenedClass(\ReflectionClass $handlerClass, string $serviceId): string
{
try {
$method = $handlerClass->getMethod('__invoke');
} catch (\ReflectionException $e) {
throw new \InvalidArgumentException(sprintf('Invalid EventListener "%s": class "%s" must have an "__invoke()" method.', $serviceId, $handlerClass->getName()));
}

$parameters = $method->getParameters();
if (1 > \count($parameters)) {
throw new \InvalidArgumentException(sprintf('Invalid EventListener "%s": method "%s::__invoke()" must have, at least, one argument corresponding to the event it handles.', $serviceId, $handlerClass->getName()));
}

if (!$type = $parameters[0]->getType()) {
throw new \InvalidArgumentException(sprintf('Invalid EventListener "%s": argument "$%s" of method "%s::__invoke()" must have a type-hint corresponding to the event class it handles.', $serviceId, $parameters[0]->getName(), $handlerClass->getName()));
}

if ($type->isBuiltin()) {
throw new \InvalidArgumentException(sprintf('Invalid EventListener "%s": type-hint of argument "$%s" in method "%s::__invoke()" must be a class, "%s" given.', $serviceId, $parameters[0]->getName(), $handlerClass->getName(), $type));
}

return $parameters[0]->getType();
}

private function registerListenerCall(ContainerBuilder $container, Definition $definition, string $listerId, string $eventName, string $method, int $priority)
{
$callable = [new ServiceClosureArgument(new Reference($listerId)), $method];
$definition->addMethodCall('addListener', [$eventName, $callable, $priority]);

if (isset($this->hotPathEvents[$eventName])) {
$container->getDefinition($listerId)->addTag($this->hotPathTagName);
}
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\EventDispatcher\DependencyInjection\RegisterListenersPass;
use Symfony\Component\HttpKernel\Event\KernelEvent;
use Symfony\Contracts\EventDispatcher\EventListenerInterface;

class RegisterListenersPassTest extends TestCase
{
Expand Down Expand Up @@ -148,6 +150,9 @@ public function testInvokableEventListener()
$container->register('foo', \stdClass::class)->addTag('kernel.event_listener', ['event' => 'foo.bar']);
$container->register('bar', InvokableListenerService::class)->addTag('kernel.event_listener', ['event' => 'foo.bar']);
$container->register('baz', InvokableListenerService::class)->addTag('kernel.event_listener', ['event' => 'event']);
$container->register('fqdn', InvokableListenerService::class)->addTag('kernel.event_listener', ['event' => KernelEvent::class]);
$container->register('autoconfigured', AutoconfiguredListenerService::class)->addTag('kernel.event_listener');
$container->register('hybride', AutoconfiguredListenerService::class)->addTag('kernel.event_listener', ['event' => 'foo'])->addTag('kernel.event_listener');
$container->register('event_dispatcher', \stdClass::class);

$registerListenersPass = new RegisterListenersPass();
Expand Down Expand Up @@ -179,6 +184,38 @@ public function testInvokableEventListener()
0,
],
],
[
'addListener',
[
'Symfony\Component\HttpKernel\Event\KernelEvent',
[new ServiceClosureArgument(new Reference('fqdn')), 'onKernelEvent'],
0,
],
],
[
'addListener',
[
'Symfony\Component\EventDispatcher\Tests\DependencyInjection\FooEvent',
[new ServiceClosureArgument(new Reference('autoconfigured')), '__invoke'],
0,
],
],
[
'addListener',
[
'foo',
[new ServiceClosureArgument(new Reference('hybride')), 'onFoo'],
0,
],
],
[
'addListener',
[
'Symfony\Component\EventDispatcher\Tests\DependencyInjection\FooEvent',
[new ServiceClosureArgument(new Reference('hybride')), '__invoke'],
0,
],
],
];
$this->assertEquals($expectedCalls, $definition->getMethodCalls());
}
Expand All @@ -203,4 +240,23 @@ public function __invoke()
public function onEvent()
{
}

public function onKernelEvent()
{
}
}

class AutoconfiguredListenerService implements EventListenerInterface
{
public function __invoke(FooEvent $e)
{
}

public function onFoo(FooEvent $e)
{
}
}

class FooEvent
{
}
23 changes: 23 additions & 0 deletions src/Symfony/Contracts/EventDispatcher/EventListenerInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?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\Contracts\EventDispatcher;

/**
* Marker interface for event listeners.
*
* @method void __invoke(object $event, string $eventName, EventDispatcherInterface $dispatcher)
*
* @author Jérémy Derussé <jeremy@derusse.com>
*/
interface EventListenerInterface
{
}
0