src/EventSubscriber/KernelTerminateSubscriber.php line 49

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\Notification;
  4. use App\Repository\NotificationRepository;
  5. use App\Service\NotificationSender;
  6. use App\Service\NotificationService;
  7. use Psr\Log\LoggerInterface;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\HttpKernel\Event\TerminateEvent;
  10. use Symfony\Component\HttpKernel\KernelEvents;
  11. class KernelTerminateSubscriber implements EventSubscriberInterface
  12. {
  13.     /** @var NotificationRepository $notificationRepository The notification data repository */
  14.     private NotificationRepository $notificationRepository;
  15.     /** @var NotificationSender $notificationSender The notification sender. */
  16.     private NotificationSender $notificationSender;
  17.     private LoggerInterface $logger;
  18.     /**
  19.      * KernelTerminateSubscriber constructor.
  20.      * @param NotificationRepository $notificationRepository
  21.      * @param NotificationSender $notificationSender
  22.      */
  23.     public function __construct(NotificationRepository $notificationRepositoryNotificationSender $notificationSenderLoggerInterface $logger)
  24.     {
  25.         $this->notificationRepository $notificationRepository;
  26.         $this->notificationSender $notificationSender;
  27.         $this->logger $logger;
  28.     }
  29.     /**
  30.      * Returns an array mapping events to functions to trigger.
  31.      * @return array The mapping array.
  32.      */
  33.     public static function getSubscribedEvents(): array
  34.     {
  35.         return [KernelEvents::TERMINATE => 'triggerDirectSendNotification'];
  36.     }
  37.     /**
  38.      * Handles the KernelTerminateEvent and sends notifications with directSend capabilities for this requies.
  39.      * @param TerminateEvent $event The KernelTerminate event.
  40.      */
  41.     public function triggerDirectSendNotification(TerminateEvent $event): void {
  42.         $request $event->getRequest();
  43.         $directSendStorage $request->attributes->get(NotificationService::NOTIFICATION_STORAGE_KEYnull);
  44.         if(false === is_null($directSendStorage)) {
  45.             foreach ($directSendStorage as $notificationId) {
  46.                 /** @var Notification $notification */
  47.                 $notification $this->notificationRepository->findOneBy(['id' => $notificationId]);
  48.                 if(false === is_null($notification)) {
  49.                     $this->notificationSender->send($notification);
  50.                 }
  51.             }
  52.             $event->getRequest()->attributes->set(NotificationService::NOTIFICATION_STORAGE_KEYnull);
  53.         }
  54.     }
  55. }