DigiComp.FlowSymfonyBridge..../Classes/EventDispatcherFactory.php

71 lines
2.8 KiB
PHP
Raw Normal View History

<?php
namespace DigiComp\FlowSymfonyBridge\Messenger;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\ObjectManagement\ObjectManagerInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
// TODO: Maybe an own package for EntityManager bridge?
class EventDispatcherFactory
{
2023-02-18 22:53:05 +01:00
#[Flow\Inject(lazy: false)]
protected ObjectManagerInterface $objectManager;
#[Flow\InjectConfiguration]
protected array $configuration;
public function create(): EventDispatcher
{
$eventDispatcher = new EventDispatcher();
foreach ($this->configuration['eventDispatcher']['subscribers'] as $subscriberId => $enabled) {
2022-09-18 13:17:53 +02:00
if ($subscriberId === null || ! (bool)$enabled) {
continue;
}
$this->addLazySubscribers($eventDispatcher, $subscriberId);
}
return $eventDispatcher;
}
2023-02-18 22:53:05 +01:00
private function addLazySubscribers(EventDispatcherInterface $eventDispatcher, $subscriberId): void
{
$subscriberClass = $this->objectManager->getClassNameByObjectName($subscriberId);
2022-09-18 13:17:53 +02:00
if (! \is_a($subscriberClass, EventSubscriberInterface::class, true)) {
throw new \RuntimeException(
'Object with name ' . $subscriberId . ' is not an EventSubscriberInterface',
1618753949
);
}
foreach ($subscriberClass::getSubscribedEvents() as $eventName => $params) {
if (\is_string($params)) {
$callClosure = function (...$arguments) use ($subscriberId, $params) {
$subscriber = $this->objectManager->get($subscriberId);
$method = $params;
return $subscriber->$method(...$arguments);
};
$eventDispatcher->addListener($eventName, $callClosure);
} elseif (\is_string($params[0])) {
$callClosure = function (...$arguments) use ($subscriberId, $params) {
$subscriber = $this->objectManager->get($subscriberId);
$method = $params[0];
return $subscriber->$method(...$arguments);
};
$eventDispatcher->addListener($eventName, $callClosure, $params[1] ?? 0);
} else {
foreach ($params as $listener) {
$callClosure = function (...$arguments) use ($subscriberId, $listener) {
$subscriber = $this->objectManager->get($subscriberId);
$method = $listener[0];
return $subscriber->$method(...$arguments);
};
$eventDispatcher->addListener($eventName, $callClosure, $listener[1] ?? 0);
}
}
}
}
}