src/EventSubscriber/MaintenanceSubscriber.php line 22

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Service\ParamService;
  4. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\RedirectResponse;
  7. use Symfony\Component\HttpKernel\Event\RequestEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. use Symfony\Component\Routing\RouterInterface;
  10. class MaintenanceSubscriber implements EventSubscriberInterface
  11. {
  12.     public function __construct(
  13.         private ParamService $paramService,
  14.         private RouterInterface $router,
  15.         private ParameterBagInterface $params
  16.     ) {
  17.     }
  18.     public function onKernelRequest(RequestEvent $event): void
  19.     {
  20.         if (!$event->isMainRequest()) {
  21.             return;
  22.         }
  23.         $maintenanceValue $this->paramService->get('site_maintenance'false);
  24.         $maintenanceEnabled filter_var($maintenanceValueFILTER_VALIDATE_BOOLEAN);
  25.         $request $event->getRequest();
  26.         $route $request->attributes->get('_route');
  27.         $path $request->getPathInfo();
  28.         if (!$maintenanceEnabled) {
  29.             if ($route === 'maintenance') {
  30.                 $event->setResponse(new RedirectResponse($this->router->generate('home')));
  31.             }
  32.             return;
  33.         }
  34.         if (
  35.             $route === 'maintenance'
  36.             || str_starts_with($path'/admin')
  37.             || str_starts_with($path'/ajax')
  38.             || str_starts_with($path'/_profiler')
  39.         ) {
  40.             return;
  41.         }
  42.         $event->setResponse(new RedirectResponse($this->router->generate('maintenance')));
  43.     }
  44.     public static function getSubscribedEvents(): array
  45.     {
  46.         return [
  47.             KernelEvents::REQUEST => ['onKernelRequest'15],
  48.         ];
  49.     }
  50. }