<?php
namespace Boldr\Cms\MaintenanceBundle\EventSubscriber;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpFoundation\Response;
use Boldr\Cms\SiteOptionsBundle\SiteOptionValueService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use Boldr\Cms\MaintenanceBundle\Event\MaintenancePageEvent;
use Boldr\Cms\MaintenanceBundle\Presenter\MaintenancePagePresenter;
use Twig\Environment;
class KernelEventSubscriber implements EventSubscriberInterface
{
private SiteOptionValueService $service;
private Environment $twig;
private MaintenancePagePresenter $maintenancePagePresenter;
private EventDispatcherInterface $eventDispatcher;
public function __construct(SiteOptionValueService $service, MaintenancePagePresenter $maintenancePagePresenter, Environment $twig, EventDispatcherInterface $eventDispatcher)
{
$this->service = $service;
$this->twig = $twig;
$this->eventDispatcher = $eventDispatcher;
$this->maintenancePagePresenter = $maintenancePagePresenter;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => [
['onKernelRequest', 0]
]
];
}
public function onKernelRequest(RequestEvent $event): void
{
$request = $event->getRequest();
$path = $request->getPathInfo();
// Exclude these paths from maintenance page so admins can still log in
foreach ([
'/boldr-admin',
'/boldr-login',
'/boldr-logout',
'/boldr-admin-api/',
'/_wdt/',
'/boldr-api/cloudprnt'
] as $allowedPath) {
if (strpos($path, $allowedPath) === 0)
{
return;
}
}
$maintenancePage = $this->service->getOption('maintenance_page');
if ($maintenancePage !== null)
{
$event2 = new MaintenancePageEvent($maintenancePage);
$this->eventDispatcher->dispatch($event2);
if ($event2->getBypassAllowed())
{
return;
}
$maintenancePageView = $this->maintenancePagePresenter->createMaintenancePageView($maintenancePage, $request->getLocale());
$assets = $maintenancePageView->getAssets();
$assets->addCssFile('/bundles/boldrmaintenance/maintenance.css');
$responseHtml = $this->twig->render('@BoldrMaintenance/maintenance.html.twig', [
'maintenancePage' => $maintenancePageView,
'assets' => $assets
]);
if ($event->getResponse() === null)
{
$event->setResponse(new Response($responseHtml));
}
}
}
}