src/EventSubscriber/NotificationSubscriber.php line 30

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(
  17.         Environment $twig,
  18.         EntityManagerInterface $em,
  19.         TokenStorageInterface $tokenStorage
  20.     ) {
  21.         $this->twig $twig;
  22.         $this->em $em;
  23.         $this->tokenStorage $tokenStorage;
  24.     }
  25.     public function onKernelRequest(RequestEvent $event)
  26.     {
  27.         if (!$event->isMasterRequest()) {
  28.             return false;
  29.         }
  30.         $token $this->tokenStorage->getToken();
  31.         if ($token === null) {
  32.             return false;
  33.         }
  34.         $user $token->getUser();
  35.         if ($user instanceof UserInterface) {
  36.             /** @var Notification[] $notifications */
  37.             $notifications $this->em->getRepository(Notification::class)->findBy([
  38.                 'user' => $user,
  39.                 'isRead' => 0,
  40.                 'type' => Notification::TYPE_NOTIFICATION,
  41.             ], ['createdAt' => 'DESC']);
  42.             $this->twig->addGlobal('widget_notifications'$notifications);
  43.         }
  44.     }
  45.     public static function getSubscribedEvents(): array
  46.     {
  47.         return array(
  48.             KernelEvents::REQUEST => 'onKernelRequest',
  49.         );
  50.     }
  51. }