src/EventListener/MaintenanceListener.php line 55

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use App\Component\Configuration\Util\Config;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Symfony\Component\HttpFoundation\RequestStack;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  8. use Symfony\Component\HttpKernel\Event\RequestEvent;
  9. use Twig\Environment;
  10. use Twig\Error\LoaderError;
  11. use Twig\Error\RuntimeError;
  12. use Twig\Error\SyntaxError;
  13. /**
  14.  * Class MaintenanceListener.
  15.  *
  16.  * Listens on the `kernel.request` event to redirect to the maintenance page is the site is set to maintenance status.
  17.  */
  18. class MaintenanceListener
  19. {
  20.     private string $debug;
  21.     private Environment $twig;
  22.     private SessionInterface $session;
  23.     private ?Request $request;
  24.     private Config $config;
  25.     public function __construct(
  26.         string $debug,
  27.         SessionInterface $session,
  28.         Environment $twig,
  29.         RequestStack $requestStack,
  30.         Config $config
  31.     ) {
  32.         $this->twig $twig;
  33.         $this->debug $debug;
  34.         $this->session $session;
  35.         $this->request $requestStack->getCurrentRequest();
  36.         $this->config $config;
  37.     }
  38.     /**
  39.      * Redirects to the maintenance page if the site is set to maintenance status.
  40.      *
  41.      * Redirects non-admin requests to the maintenance page if
  42.      *  1. the site is set to maintenance status,
  43.      *  2. the site is not in dev environment, and
  44.      *  3. the user is not logged in (and is thus granted access).
  45.      *
  46.      * @throws LoaderError
  47.      * @throws RuntimeError
  48.      * @throws SyntaxError
  49.      */
  50.     public function onKernelRequest(RequestEvent $event)
  51.     {
  52.         // this is needed until code is seperated
  53.         if (=== strncmp($this->request->getRequestUri(), '/admin'6)) {
  54.             return;
  55.         }
  56.         // This will get the value of our maintenance parameter
  57.         $maintenance 'maintenance' === $this->config->get('site_status');
  58.         // If maintenance is active and in prod environment
  59.         if ($maintenance && !$this->debug && !$this->session->get('site_access')) {
  60.             $response $this->twig->render(
  61.                 '@default/pages/maintenance.html.twig',
  62.                 ['maintenanceBody' => $this->config->get('site_maintenance_body')]
  63.             );
  64.             // We send our response with a 503 response code (service unavailable)
  65.             $event->setResponse(new Response($response503));
  66.         }
  67.     }
  68. }