MaintenanceModeSubscriber.php in Drupal 9
File
core/modules/user/src/EventSubscriber/MaintenanceModeSubscriber.php
View source
<?php
namespace Drupal\user\EventSubscriber;
use Drupal\Core\Routing\RouteMatch;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Site\MaintenanceModeInterface;
use Drupal\Core\Url;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class MaintenanceModeSubscriber implements EventSubscriberInterface {
protected $maintenanceMode;
protected $account;
public function __construct(MaintenanceModeInterface $maintenance_mode, AccountInterface $account) {
$this->maintenanceMode = $maintenance_mode;
$this->account = $account;
}
public function onKernelRequestMaintenance(RequestEvent $event) {
$request = $event
->getRequest();
$route_match = RouteMatch::createFromRequest($request);
if ($this->maintenanceMode
->applies($route_match)) {
if ($this->account
->isAuthenticated() && !$this->maintenanceMode
->exempt($this->account)) {
user_logout();
$event
->setResponse(new RedirectResponse(Url::fromRoute('<front>')
->toString()));
}
}
}
public static function getSubscribedEvents() {
$events[KernelEvents::REQUEST][] = [
'onKernelRequestMaintenance',
31,
];
return $events;
}
}