<?php
namespace FMT\Domain\Listener;
use FMT\Data\Entity\User;
use FMT\Domain\Repository\UserNotificationsRepositoryInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class UserNotificationListener
{
private UserNotificationsRepositoryInterface $userNotificationsRepository;
private SessionInterface $session;
private TokenStorageInterface $tokenStorage;
public function __construct(
UserNotificationsRepositoryInterface $userNotificationsRepository,
SessionInterface $session,
TokenStorageInterface $tokenStorage
) {
$this->userNotificationsRepository = $userNotificationsRepository;
$this->session = $session;
$this->tokenStorage = $tokenStorage;
}
public function onKernelRequest(RequestEvent $event)
{
$tokenStorage = $this->tokenStorage->getToken();
if (!$tokenStorage) {
return;
}
/** @var ?User $user */
$user = $tokenStorage->getUser();
if (!$user instanceof User) {
return;
}
$notifications = $this->userNotificationsRepository->findUserNotifications($user);
foreach ($notifications as $notification) {
$this->session->getFlashBag()->add('warning', $notification->getMessage());
$notification->setIsSent(1);
$this->userNotificationsRepository->add($notification);
$this->userNotificationsRepository->save($notification);
}
}
}