src/EventSubscriber/KernelRequestSubscriber.php line 39

  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\Response;
  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 Twig\Environment as TwigEnvironment;
  10. class KernelRequestSubscriber implements EventSubscriberInterface
  11. {
  12.     private TwigEnvironment $twig;
  13.     private TokenStorageInterface $tokenStorage;  // <-- Changez ceci
  14.     public function __construct(
  15.         TwigEnvironment $twig,
  16.         TokenStorageInterface $tokenStorage  // <-- Et ceci
  17.     ){
  18.         $this->twig $twig;
  19.         $this->tokenStorage $tokenStorage;
  20.     }
  21.     /**
  22.      * {@inheritdoc}
  23.      */
  24.     public static function getSubscribedEvents(): array
  25.     {
  26.         return [
  27.             KernelEvents::REQUEST => [
  28.                 ['onMaintenance'\PHP_INT_MAX 1000],
  29.             ],
  30.         ];
  31.     }
  32.     public function onMaintenance(RequestEvent $event): void
  33.     {
  34.         // VĂ©rifier si on est sur une route admin
  35.         $request $event->getRequest();
  36.         $pathInfo $request->getPathInfo();
  37.         
  38.         if (str_starts_with($pathInfo'/admin')) {
  39.             return;
  40.         }
  41.         /** @var bool $isMaintenance */
  42.         $isMaintenance \filter_var($_ENV['MAINTENANCE_MODE'] ?? '0'\FILTER_VALIDATE_BOOLEAN);
  43.         $whitelistedIps = ['127.0.0.1','86.207.232.56''88.124.138.142''45.145.167.57''37.122.207.67'];
  44.         if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
  45.             $ip $_SERVER['HTTP_CLIENT_IP'];
  46.         } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  47.             $ip $_SERVER['HTTP_X_FORWARDED_FOR'];
  48.         } else {
  49.             $ip $_SERVER['REMOTE_ADDR'];
  50.         }
  51.         
  52.         if(!in_array($ip,$whitelistedIps)) {
  53.             if ($isMaintenance) {
  54.                 $event->setResponse(new Response(
  55.                     $this->twig->render('maintenance.html.twig'),
  56.                     Response::HTTP_SERVICE_UNAVAILABLE,
  57.                 ));
  58.                 $event->stopPropagation();
  59.             }
  60.         }
  61.     }
  62. }