<?php
namespace App\EventSubscriber;
use App\Entity\Notification;
use App\Repository\NotificationRepository;
use App\Service\NotificationSender;
use App\Service\NotificationService;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\TerminateEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class KernelTerminateSubscriber implements EventSubscriberInterface
{
/** @var NotificationRepository $notificationRepository The notification data repository */
private NotificationRepository $notificationRepository;
/** @var NotificationSender $notificationSender The notification sender. */
private NotificationSender $notificationSender;
private LoggerInterface $logger;
/**
* KernelTerminateSubscriber constructor.
* @param NotificationRepository $notificationRepository
* @param NotificationSender $notificationSender
*/
public function __construct(NotificationRepository $notificationRepository, NotificationSender $notificationSender, LoggerInterface $logger)
{
$this->notificationRepository = $notificationRepository;
$this->notificationSender = $notificationSender;
$this->logger = $logger;
}
/**
* Returns an array mapping events to functions to trigger.
* @return array The mapping array.
*/
public static function getSubscribedEvents(): array
{
return [KernelEvents::TERMINATE => 'triggerDirectSendNotification'];
}
/**
* Handles the KernelTerminateEvent and sends notifications with directSend capabilities for this requies.
* @param TerminateEvent $event The KernelTerminate event.
*/
public function triggerDirectSendNotification(TerminateEvent $event): void {
$request = $event->getRequest();
$directSendStorage = $request->attributes->get(NotificationService::NOTIFICATION_STORAGE_KEY, null);
if(false === is_null($directSendStorage)) {
foreach ($directSendStorage as $notificationId) {
/** @var Notification $notification */
$notification = $this->notificationRepository->findOneBy(['id' => $notificationId]);
if(false === is_null($notification)) {
$this->notificationSender->send($notification);
}
}
$event->getRequest()->attributes->set(NotificationService::NOTIFICATION_STORAGE_KEY, null);
}
}
}