MaintenanceModeSubscriber.php 2.04 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\user\EventSubscriber;

5
use Drupal\Core\Routing\RouteMatch;
6
use Drupal\Core\Routing\UrlGeneratorTrait;
7 8
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Site\MaintenanceModeInterface;
9 10 11 12 13 14 15 16 17
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Maintenance mode subscriber to logout users.
 */
class MaintenanceModeSubscriber implements EventSubscriberInterface {

18 19
  use UrlGeneratorTrait;

20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
  /**
   * The maintenance mode.
   *
   * @var \Drupal\Core\Site\MaintenanceMode
   */
  protected $maintenanceMode;

  /**
   * The current account.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $account;

  /**
   * Constructs a new MaintenanceModeSubscriber.
   *
   * @param \Drupal\Core\Site\MaintenanceModeInterface $maintenance_mode
   *   The maintenance mode.
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The current user.
   */
  public function __construct(MaintenanceModeInterface $maintenance_mode, AccountInterface $account) {
    $this->maintenanceMode = $maintenance_mode;
    $this->account = $account;
  }

47
  /**
48
   * Logout users if site is in maintenance mode.
49 50 51 52 53 54
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
   *   The event to process.
   */
  public function onKernelRequestMaintenance(GetResponseEvent $event) {
    $request = $event->getRequest();
55 56
    $route_match = RouteMatch::createFromRequest($request);
    if ($this->maintenanceMode->applies($route_match)) {
57
      // If the site is offline, log out unprivileged users.
58
      if ($this->account->isAuthenticated() && !$this->maintenanceMode->exempt($this->account)) {
59 60
        user_logout();
        // Redirect to homepage.
61
        $event->setResponse($this->redirect($this->url('<front>')));
62 63 64 65 66 67 68 69
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
70
    $events[KernelEvents::REQUEST][] = ['onKernelRequestMaintenance', 31];
71 72 73 74
    return $events;
  }

}