src/EventSubscriber/NotificationTwigSubscriber.php line 34

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Repository\UserNotificationRepository;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  6. use Symfony\Component\HttpKernel\KernelEvents;
  7. use Symfony\Component\Security\Core\Security;
  8. use Twig\Environment;
  9. /**
  10.  * Injecte automatiquement dans tous les templates Twig :
  11.  * - unreadNotifCount : nb de notifs non lues
  12.  * - recentNotifs     : les 5 dernières notifs non lues
  13.  * - fcm_vapid_key    : clé VAPID pour FCM web
  14.  */
  15. class NotificationTwigSubscriber implements EventSubscriberInterface
  16. {
  17.     public function __construct(
  18.         private Security $security,
  19.         private UserNotificationRepository $notifRepo,
  20.         private Environment $twig,
  21.         private string $fcmVapidKey   // injecté depuis services.yaml
  22.     ) {}
  23.     public static function getSubscribedEvents(): array
  24.     {
  25.         return [
  26.             KernelEvents::CONTROLLER => 'onKernelController',
  27.         ];
  28.     }
  29.     public function onKernelController(ControllerEvent $event): void
  30.     {
  31.         if (!$event->isMainRequest()) { return; }
  32.         $user $this->security->getUser();
  33.         if (!$user) { return; }
  34.         // Seulement pour les admins/editors
  35.         if (!in_array('ROLE_ADMIN'$user->getRoles())
  36.             && !in_array('ROLE_EDITOR'$user->getRoles())) {
  37.             return;
  38.         }
  39.         $unreadCount  $this->notifRepo->count(['user' => $user'isRead' => false]);
  40.         $recentNotifs $this->notifRepo->findBy(
  41.             ['user' => $user'isRead' => false],
  42.             ['id' => 'DESC'],
  43.             5
  44.         );
  45.         $this->twig->addGlobal('unreadNotifCount'$unreadCount);
  46.         $this->twig->addGlobal('recentNotifs'$recentNotifs);
  47.         $this->twig->addGlobal('fcm_vapid_key'$this->fcmVapidKey);
  48.     }
  49. }