8000 [EventDispatcher] Improve method resolving when it is omitted in tag by nikophil · Pull Request #50783 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[EventDispatcher] Improve method resolving when it is omitted in tag #50783

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

Open
wants to merge 1 commit into
base: 7.4
Choose a base branch
from
Open
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 @@ -80,19 +80,7 @@ public function process(ContainerBuilder $container): void
$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',
], fn ($matches) => strtoupper($matches[0]), $event['event']);
$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'])) {
if (!$r->hasMethod('__invoke')) {
throw new InvalidArgumentException(\sprintf('None of the "%s" or "__invoke" methods exist for the service "%s". Please define the "method" attribute on "kernel.event_listener" tags.', $event['method'], $id));
}

$event['method'] = '__invoke';
}
$event['method'] = $this->resolveListenerMethodFromTypeDeclaration($container, $id, $event['event'], $aliases);
}

$dispatcherDefinition = $globalDispatcherDefinition;
Expand Down Expand Up @@ -183,6 +171,54 @@ private function getEventFromTypeDeclaration(ContainerBuilder $container, string

return $name;
}

/**
* Resolve the listener method:
* - look for a method named after the event (camelized, with "on" prefix)
* - if such a method does not exist, check if only one public method exist which expect the event as parameter
* - otherwise, throw an exception because we need more information.
*/
private function resolveListenerMethodFromTypeDeclaration(ContainerBuilder $container, string $id, string $eventName, array $aliases): string
{
$method = 'on'.preg_replace_callback([
'/(?<=\b|_)[a-z]/i',
'/[^a-z0-9]/i',
], fn ($matches) => strtoupper($matches[0]), $eventName);
$method = preg_replace('/[^a-z0-9]/i', '', $method);

if (
null === ($class = $container->getDefinition($id)->getClass())
|| !($r = $container->getReflectionClass($class, false))
|| $r->hasMethod($method)
) {
return $method;
}

$publicMethods = $r->getMethods(\ReflectionMethod::IS_PUBLIC);
$eventName = array_flip($aliases)[$eventName] ?? $eventName;

$candidateMethods = [];
foreach ($publicMethods as $publicMethod) {
if (
!$publicMethod->isStatic()
&& 1 === $publicMethod->getNumberOfRequiredParameters()
Copy link
Member

Choose a reason for hiding this comment

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

This check is bad given that the EventDispatcher component actually provides 3 parameters to listeners:

  • the event object
  • the event name
  • the EventDispatcher instance

&& ($type = $publicMethod->getParameters()[0]->getType()) instanceof \ReflectionNamedType
&& is_a($eventName, $type->getName(), allow_string: true)
) {
$candidateMethods[] = $publicMethod->getName();
}
}

if (1 === \count($candidateMethods)) {
return $candidateMethods[0];
}

if ($r->hasMethod('__invoke')) {
return '__invoke';
}

throw new InvalidArgumentException(\sprintf('Service "%s" is missing a "method" attribute on "kernel.event_listener" tags.', $id));
}
}

/**
Expand Down
10000
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,13 @@ public function onFooBarZar()
{
}
}))->addTag('kernel.event_listener', ['event' => 'foo.bar_zar']);
$container->register('typed_listener', InvokableListenerService::class)->addTag('kernel.event_listener', ['event' => CustomEvent::class]);
$container->register('aliased_event', InvokableListenerService::class)->addTag('kernel.event_listener', ['event' => 'aliased_event']);
$container->register('child_event', \get_class(new class {
public function __invoke(ParentEvent $event)
{
}
}))->addTag('kernel.event_listener', ['event' => ChildEvent::class]);
$container->register('event_dispatcher', \stdClass::class);

$registerListenersPass = new RegisterListenersPass();
Expand Down Expand Up @@ -253,18 +260,68 @@ public function onFooBarZar()
0,
],
],
[
'addListener',
[
CustomEvent::class,
[new ServiceClosureArgument(new Reference('typed_listener')), 'onCustomEvent'],
0,
],
],
[
'addListener',
[
'aliased_event',
[new ServiceClosureArgument(new Reference('aliased_event')), 'onAliasedEvent'],
0,
],
],
[
'addListener',
[
ChildEvent::class,
[new ServiceClosureArgument(new Reference('child_event')), '__invoke'],
0,
],
],
];
$this->assertEquals($expectedCalls, $definition->getMethodCalls());
}

public function testItThrowsAnExceptionIfTagIsMissingMethodAndClassHasNoValidMethod()
public function testItThrowsAnExceptionIfTagIsMissingMethodAndClassHasMultipleMethodsWithEvent()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Service "foo" is missing a "method" attribute on "kernel.event_listener" tags.');

$container = new ContainerBuilder();

$container->register('foo', \get_class(new class {
public function doSomethingOnCustomEvent(CustomEvent $event)
{
}

public function doAnotherThingOnCustomEvent(CustomEvent $event)
{
}
}))->addTag('kernel.event_listener', ['event' => CustomEvent::class]);
$container->register('event_dispatcher', \stdClass::class);

$registerListenersPass = new RegisterListenersPass();
$registerListenersPass->process($container);
}

public function testItThrowsAnExceptionIfTagIsMissingMethodAndClassHasNoMethodWithEvent()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('None of the "onFooBar" or "__invoke" methods exist for the service "foo". Please define the "method" attribute on "kernel.event_listener" tags.');
$this->expectExceptionMessage('Service "foo" is missing a "method" attribute on "kernel.event_listener" tags.');

$container = new ContainerBuilder();

$container->register('foo', \stdClass::class)->addTag('kernel.event_listener', ['event' => 'foo.bar']);
$container->register('foo', \get_class(new class {
public function doSomethingOnCustomEvent($event)
{
}
}))->addTag('kernel.event_listener', ['event' => CustomEvent::class]);
$container->register('event_dispatcher', \stdClass::class);

$registerListenersPass = new RegisterListenersPass();
Expand Down Expand Up @@ -524,6 +581,14 @@ public function __invoke()
public function onEvent()
{
}

public function onCustomEvent(CustomEvent $event): void
{
}

public function onAliasedEvent(AliasedEvent $event): void
{
}
}

final class AliasedSubscriber implements EventSubscriberInterface
Expand All @@ -541,6 +606,14 @@ final class AliasedEvent
{
}

class ParentEvent
{
}

final class ChildEvent extends ParentEvent
{
}

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