src/App/EventSubscriber/MaintenanceModeSubscriber.php line 30

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\RedirectResponse;
  6. use Symfony\Component\HttpKernel\Event\RequestEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. /**
  9. * Subscriber that redirects to maintenance page when maintenance mode is active.
  10. *
  11. * Checks the STAY_APPLICATION_MAINTENANCE_MODE constant/env variable
  12. * and redirects to /maintenance if enabled.
  13. */
  14. class MaintenanceModeSubscriber implements EventSubscriberInterface
  15. {
  16. private const MAINTENANCE_ROUTE = '/maintenance';
  17. private const ALLOWED_ROUTES = ['/maintenance', '/liveness'];
  18. public static function getSubscribedEvents(): array
  19. {
  20. return [
  21. KernelEvents::REQUEST => ['onKernelRequest', 100], // High priority to run early
  22. ];
  23. }
  24. public function onKernelRequest(RequestEvent $event): void
  25. {
  26. if (!$event->isMainRequest()) {
  27. return;
  28. }
  29. // Check if maintenance mode is enabled
  30. if (!$this->isMaintenanceModeEnabled()) {
  31. return;
  32. }
  33. $request = $event->getRequest();
  34. $path = $request->getPathInfo();
  35. // Allow certain routes even in maintenance mode
  36. foreach (self::ALLOWED_ROUTES as $allowedRoute) {
  37. if (str_starts_with($path, $allowedRoute)) {
  38. return;
  39. }
  40. }
  41. // Redirect to maintenance page
  42. $event->setResponse(new RedirectResponse(self::MAINTENANCE_ROUTE));
  43. }
  44. private function isMaintenanceModeEnabled(): bool
  45. {
  46. // Check constant first (defined in www/index.php)
  47. if (defined('STAY_APPLICATION_MAINTENANCE_MODE')) {
  48. $value = constant('STAY_APPLICATION_MAINTENANCE_MODE');
  49. return $value === 'true' || $value === true || $value === '1';
  50. }
  51. // Fallback to env variable
  52. $envValue = getenv('STAY_APPLICATION_MAINTENANCE_MODE');
  53. return $envValue === 'true' || $envValue === '1';
  54. }
  55. }