src/Twig/UserNotifications.php line 30

  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Twig;
  4. use App\Repository\NotificationRepository;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpKernel\KernelEvents;
  7. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  8. use Twig\Environment;
  9. final class UserNotifications implements EventSubscriberInterface
  10. {
  11.     public function __construct(
  12.         private readonly Environment $twig,
  13.         private readonly TokenStorageInterface $storage,
  14.         private readonly NotificationRepository $notificationRepository
  15.     )
  16.     {
  17.     }
  18.     public static function getSubscribedEvents(): array
  19.     {
  20.         return [
  21.             KernelEvents::CONTROLLER => 'getNotifications'
  22.         ];
  23.     }
  24.     public function getNotifications(): void
  25.     {
  26.         $token $this->storage->getToken();
  27.         if ($token) {
  28.             $user $token->getUser();
  29.             if (null === $user) {
  30.                 return;
  31.             }
  32.             $notifications $this->notificationRepository->getLastThree($user);
  33.             $this->twig->addGlobal('lastNotifications'$notifications);
  34.         }
  35.     }
  36. }