src/Products/NotificationsBundle/Subscriber/AutomationSubscriber.php line 51

Open in your IDE?
  1. <?php
  2. namespace Products\NotificationsBundle\Subscriber;
  3. use Cms\CoreBundle\Util\Doctrine\EntityManager;
  4. use DateTime;
  5. use Platform\QueueBundle\Event\AsyncEvent;
  6. use Products\NotificationsBundle\Entity\Automation;
  7. use Products\NotificationsBundle\Entity\Notifications\Invocation;
  8. use Products\NotificationsBundle\Entity\Notifications\Template;
  9. use Products\NotificationsBundle\Service\MessageLogic;
  10. use Products\NotificationsBundle\Service\Switchboard;
  11. use RuntimeException;
  12. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  13. final class AutomationSubscriber implements EventSubscriberInterface
  14. {
  15.     /**
  16.      * @var EntityManager
  17.      */
  18.     protected EntityManager $em;
  19.     /**
  20.      * @var MessageLogic
  21.      */
  22.     protected MessageLogic $messageLogic;
  23.     /**
  24.      * @param EntityManager $em
  25.      * @param MessageLogic $messageLogic
  26.      */
  27.     public function __construct(EntityManager $emMessageLogic $messageLogic)
  28.     {
  29.         $this->em $em;
  30.         $this->messageLogic $messageLogic;
  31.     }
  32.     /**
  33.      * {@inheritDoc}
  34.      */
  35.     public static function getSubscribedEvents(): array
  36.     {
  37.         return [
  38.             Switchboard::EVENTS__BROADCAST_AUTOMATION => ['onBroadcastAutomation'0],
  39.         ];
  40.     }
  41.     /**
  42.      * @param AsyncEvent $event
  43.      */
  44.     public function onBroadcastAutomation(AsyncEvent $event): void
  45.     {
  46.         $automation $this->em->getRepository(Automation::class)->find(
  47.             $event->getBody()->get('automation')
  48.         );
  49.         if ( ! $automation instanceof Automation) {
  50.             throw new RuntimeException();
  51.         }
  52.         if ( ! $automation->getTemplate() instanceof Template) {
  53.             throw new RuntimeException();
  54.         }
  55.         $this->messageLogic->broadcast($this->createInvocation($automation));
  56.     }
  57.     /**
  58.      * @param Automation $automation
  59.      * @return Invocation
  60.      */
  61.     private function createInvocation(Automation $automation): Invocation
  62.     {
  63.         $invocation = new Invocation();
  64.         $invocation->setAutomation($automation);
  65.         $invocation->setConditionQuery($automation->getRunnableConditionQuery());
  66.         $invocation->setInvocationTimestamp(new DateTime());
  67.         $this->messageLogic->init($invocation$automation->getTemplate());
  68.         $this->em->save($invocation);
  69.         return $invocation;
  70.     }
  71. }