<?php
namespace App\EventSubscriber;
use App\Repository\UserNotificationRepository;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Security;
use Twig\Environment;
/**
* Injecte automatiquement dans tous les templates Twig :
* - unreadNotifCount : nb de notifs non lues
* - recentNotifs : les 5 dernières notifs non lues
* - fcm_vapid_key : clé VAPID pour FCM web
*/
class NotificationTwigSubscriber implements EventSubscriberInterface
{
public function __construct(
private Security $security,
private UserNotificationRepository $notifRepo,
private Environment $twig,
private string $fcmVapidKey // injecté depuis services.yaml
) {}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::CONTROLLER => 'onKernelController',
];
}
public function onKernelController(ControllerEvent $event): void
{
if (!$event->isMainRequest()) { return; }
$user = $this->security->getUser();
if (!$user) { return; }
// Seulement pour les admins/editors
if (!in_array('ROLE_ADMIN', $user->getRoles())
&& !in_array('ROLE_EDITOR', $user->getRoles())) {
return;
}
$unreadCount = $this->notifRepo->count(['user' => $user, 'isRead' => false]);
$recentNotifs = $this->notifRepo->findBy(
['user' => $user, 'isRead' => false],
['id' => 'DESC'],
5
);
$this->twig->addGlobal('unreadNotifCount', $unreadCount);
$this->twig->addGlobal('recentNotifs', $recentNotifs);
$this->twig->addGlobal('fcm_vapid_key', $this->fcmVapidKey);
}
}