<?php
namespace App\EventSubscriber;
use App\Entity\Notification;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Twig\Environment;
class NotificationSubscriber implements EventSubscriberInterface
{
private Environment $twig;
private EntityManagerInterface $em;
private TokenStorageInterface $tokenStorage;
public function __construct(Environment $twig, EntityManagerInterface $em, TokenStorageInterface $tokenStorage)
{
$this->twig = $twig;
$this->em = $em;
$this->tokenStorage = $tokenStorage;
}
public function onKernelRequest(RequestEvent $event)
{
if (!$event->isMainRequest()) {
return false;
}
$token = $this->tokenStorage->getToken();
if ($token === null) {
return false;
}
$user = $token->getUser();
if ($user instanceof UserInterface) {
/** @var Notification[] $notifications */
$notifications = $this->em->getRepository(Notification::class)->findBy([
'user' => $user,
'isRead' => 0,
'type' => Notification::TYPE_NOTIFICATION,
], ['createdAt' => 'DESC']);
$this->twig->addGlobal('widget_notifications', $notifications);
}
}
public static function getSubscribedEvents(): array
{
return array(
KernelEvents::REQUEST => 'onKernelRequest',
);
}
}