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

namespace Drupal\user\EventSubscriber;

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

/**
15
 * Maintenance mode subscriber to log out users.
16 17 18
 */
class MaintenanceModeSubscriber implements EventSubscriberInterface {

19 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
  /**
   * 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;
  }

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

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

}