Support "AsMessageHandler"-Attribute for autoconfiguration

This commit is contained in:
Ferdinand Kuhl 2023-01-05 18:08:46 +01:00
parent ed4cf1b39a
commit dc00f8b7d6
2 changed files with 25 additions and 7 deletions

View file

@ -5,6 +5,7 @@ namespace DigiComp\FlowSymfonyBridge\Messenger;
use Neos\Flow\Annotations as Flow; use Neos\Flow\Annotations as Flow;
use Neos\Flow\ObjectManagement\ObjectManagerInterface; use Neos\Flow\ObjectManagement\ObjectManagerInterface;
use Neos\Flow\Reflection\ReflectionService; use Neos\Flow\Reflection\ReflectionService;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Messenger\Handler\HandlerDescriptor; use Symfony\Component\Messenger\Handler\HandlerDescriptor;
use Symfony\Component\Messenger\Handler\HandlersLocator; use Symfony\Component\Messenger\Handler\HandlersLocator;
use Symfony\Component\Messenger\Handler\MessageSubscriberInterface; use Symfony\Component\Messenger\Handler\MessageSubscriberInterface;
@ -50,6 +51,27 @@ class HandlersLocatorFactory
); );
} }
} }
$asHandlerClasses = $this->reflectionService
->getClassNamesByAnnotation(AsMessageHandler::class);
foreach ($asHandlerClasses as $asHandlerClass) {
/** @var AsMessageHandler $annotation */
$annotation = $this->reflectionService->getClassAnnotation($asHandlerClass, AsMessageHandler::class);
$config['from_transport'] = $annotation->fromTransport;
$config['priority'] = $annotation->priority;
$method = $annotation->method ?? '__invoke';
$messageName = $annotation->handles;
if ($messageName === null) {
$arguments = $this->reflectionService->getMethodParameters($asHandlerClass, $method);
$messageName = $arguments[\array_key_first($arguments)]['class'];
}
if ($annotation->bus !== null && $annotation->bus !== $busName) {
continue;
}
$handlerDescriptors[$messageName][] = new HandlerDescriptor(
$this->objectManager->get($asHandlerClass),
$config
);
}
// TODO: Maybe we can allow handlers to be added to bus or globally by configuration? // TODO: Maybe we can allow handlers to be added to bus or globally by configuration?
return new HandlersLocator($handlerDescriptors); return new HandlersLocator($handlerDescriptors);

View file

@ -2,15 +2,11 @@
namespace DigiComp\FlowSymfonyBridge\Messenger\Tests\Functional\Fixtures\Message; namespace DigiComp\FlowSymfonyBridge\Messenger\Tests\Functional\Fixtures\Message;
use Symfony\Component\Messenger\Handler\MessageSubscriberInterface; use Symfony\Component\Messenger\Attribute\AsMessageHandler;
class TestMessageHandler implements MessageSubscriberInterface #[AsMessageHandler]
class TestMessageHandler
{ {
public static function getHandledMessages(): iterable
{
yield TestMessage::class => [];
}
public function __invoke(TestMessage $message) public function __invoke(TestMessage $message)
{ {
//do nothing for now //do nothing for now