<?php
namespace Products\NotificationsBundle\Subscriber;
use Cms\CoreBundle\Util\Doctrine\EntityManager;
use DateTime;
use Platform\QueueBundle\Event\AsyncEvent;
use Products\NotificationsBundle\Entity\Automation;
use Products\NotificationsBundle\Entity\Notifications\Invocation;
use Products\NotificationsBundle\Entity\Notifications\Template;
use Products\NotificationsBundle\Service\MessageLogic;
use Products\NotificationsBundle\Service\Switchboard;
use RuntimeException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
final class AutomationSubscriber implements EventSubscriberInterface
{
/**
* @var EntityManager
*/
protected EntityManager $em;
/**
* @var MessageLogic
*/
protected MessageLogic $messageLogic;
/**
* @param EntityManager $em
* @param MessageLogic $messageLogic
*/
public function __construct(EntityManager $em, MessageLogic $messageLogic)
{
$this->em = $em;
$this->messageLogic = $messageLogic;
}
/**
* {@inheritDoc}
*/
public static function getSubscribedEvents(): array
{
return [
Switchboard::EVENTS__BROADCAST_AUTOMATION => ['onBroadcastAutomation', 0],
];
}
/**
* @param AsyncEvent $event
*/
public function onBroadcastAutomation(AsyncEvent $event): void
{
$automation = $this->em->getRepository(Automation::class)->find(
$event->getBody()->get('automation')
);
if ( ! $automation instanceof Automation) {
throw new RuntimeException();
}
if ( ! $automation->getTemplate() instanceof Template) {
throw new RuntimeException();
}
$this->messageLogic->broadcast($this->createInvocation($automation));
}
/**
* @param Automation $automation
* @return Invocation
*/
private function createInvocation(Automation $automation): Invocation
{
$invocation = new Invocation();
$invocation->setAutomation($automation);
$invocation->setConditionQuery($automation->getRunnableConditionQuery());
$invocation->setInvocationTimestamp(new DateTime());
$this->messageLogic->init($invocation, $automation->getTemplate());
$this->em->save($invocation);
return $invocation;
}
}