src/EventSubscriber/NotificationSubscriber.php line 27

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\Notification;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpKernel\Event\RequestEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  9. use Symfony\Component\Security\Core\User\UserInterface;
  10. use Twig\Environment;
  11. class NotificationSubscriber implements EventSubscriberInterface
  12. {
  13.     private Environment $twig;
  14.     private EntityManagerInterface $em;
  15.     private TokenStorageInterface $tokenStorage;
  16.     public function __construct(Environment $twigEntityManagerInterface $emTokenStorageInterface $tokenStorage)
  17.     {
  18.         $this->twig $twig;
  19.         $this->em $em;
  20.         $this->tokenStorage $tokenStorage;
  21.     }
  22.     public function onKernelRequest(RequestEvent $event)
  23.     {
  24.         if (!$event->isMainRequest()) {
  25.             return false;
  26.         }
  27.         $token $this->tokenStorage->getToken();
  28.         if ($token === null) {
  29.             return false;
  30.         }
  31.         $user $token->getUser();
  32.         if ($user instanceof UserInterface) {
  33.             /** @var Notification[] $notifications */
  34.             $notifications $this->em->getRepository(Notification::class)->findBy([
  35.                 'user' => $user,
  36.                 'isRead' => 0,
  37.                 'type' => Notification::TYPE_NOTIFICATION,
  38.             ], ['createdAt' => 'DESC']);
  39.             $this->twig->addGlobal('widget_notifications'$notifications);
  40.         }
  41.     }
  42.     public static function getSubscribedEvents(): array
  43.     {
  44.         return array(
  45.             KernelEvents::REQUEST => 'onKernelRequest',
  46.         );
  47.     }
  48. }