src/EventSubscriber/AgendaReminderDispatchSubscriber.php line 36

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Service\AgendaReminderService;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. use Symfony\Contracts\Cache\CacheInterface;
  9. use Symfony\Contracts\Cache\ItemInterface;
  10. /**
  11.  * Déclenche l'envoi des rappels agenda à la volée (sans cron),
  12.  * avec un throttling global pour éviter d'exécuter la tâche à chaque requête.
  13.  */
  14. class AgendaReminderDispatchSubscriber implements EventSubscriberInterface
  15. {
  16.     private const CACHE_KEY 'agenda_reminders.last_dispatch';
  17.     private const DISPATCH_INTERVAL_SECONDS 60;
  18.     private const DISPATCH_LIMIT 150;
  19.     public function __construct(
  20.         private readonly AgendaReminderService $agendaReminderService,
  21.         private readonly CacheInterface $cache,
  22.     ) {
  23.     }
  24.     public static function getSubscribedEvents(): array
  25.     {
  26.         return [
  27.             KernelEvents::CONTROLLER => ['onKernelController'0],
  28.         ];
  29.     }
  30.     public function onKernelController(ControllerEvent $event): void
  31.     {
  32.         if (!$event->isMainRequest()) {
  33.             return;
  34.         }
  35.         $request $event->getRequest();
  36.         if ($this->isStaticAsset($request)) {
  37.             return;
  38.         }
  39.         $now time();
  40.         $last = (int) $this->cache->get(self::CACHE_KEY, static function (ItemInterface $item) {
  41.             $item->expiresAfter(3600);
  42.             return 0;
  43.         });
  44.         if ($now $last self::DISPATCH_INTERVAL_SECONDS) {
  45.             return;
  46.         }
  47.         $this->cache->delete(self::CACHE_KEY);
  48.         $this->cache->get(self::CACHE_KEY, static function (ItemInterface $item) use ($now) {
  49.             $item->expiresAfter(3600);
  50.             return $now;
  51.         });
  52.         try {
  53.             $this->agendaReminderService->dispatchDueReminders(self::DISPATCH_LIMIT);
  54.         } catch (\Throwable $exception) {
  55.             // Ne pas bloquer la requête en cas d'erreur d'envoi des rappels.
  56.         }
  57.     }
  58.     private function isStaticAsset(Request $request): bool
  59.     {
  60.         $path $request->getPathInfo();
  61.         return (bool) preg_match('#^/(build|assets|css|js|fonts|img|images|favicon\\.ico|robots\\.txt|_wdt|_profiler)#'$path);
  62.     }
  63. }