<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Subscriber that redirects to maintenance page when maintenance mode is active.
*
* Checks the STAY_APPLICATION_MAINTENANCE_MODE constant/env variable
* and redirects to /maintenance if enabled.
*/
class MaintenanceModeSubscriber implements EventSubscriberInterface
{
private const MAINTENANCE_ROUTE = '/maintenance';
private const ALLOWED_ROUTES = ['/maintenance', '/liveness'];
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => ['onKernelRequest', 100], // High priority to run early
];
}
public function onKernelRequest(RequestEvent $event): void
{
if (!$event->isMainRequest()) {
return;
}
// Check if maintenance mode is enabled
if (!$this->isMaintenanceModeEnabled()) {
return;
}
$request = $event->getRequest();
$path = $request->getPathInfo();
// Allow certain routes even in maintenance mode
foreach (self::ALLOWED_ROUTES as $allowedRoute) {
if (str_starts_with($path, $allowedRoute)) {
return;
}
}
// Redirect to maintenance page
$event->setResponse(new RedirectResponse(self::MAINTENANCE_ROUTE));
}
private function isMaintenanceModeEnabled(): bool
{
// Check constant first (defined in www/index.php)
if (defined('STAY_APPLICATION_MAINTENANCE_MODE')) {
$value = constant('STAY_APPLICATION_MAINTENANCE_MODE');
return $value === 'true' || $value === true || $value === '1';
}
// Fallback to env variable
$envValue = getenv('STAY_APPLICATION_MAINTENANCE_MODE');
return $envValue === 'true' || $envValue === '1';
}
}