You are here

public function PagesRestrictionSubscriber::onRequestCheckRestrictedPages in Pages Restriction Access 8

On Request Check Restricted Pages.

File

src/Event/PagesRestrictionSubscriber.php, line 98

Class

PagesRestrictionSubscriber
Default class for Subscriber.

Namespace

Drupal\pages_restriction\Event

Code

public function onRequestCheckRestrictedPages(GetResponseEvent $event) {
  $config = $this->configFactory
    ->get('pages_restriction.settings');
  $roles = $this->account
    ->getRoles();
  $bypass_role = $config
    ->get('bypass_role');

  // Check bypass only for logged user.
  if (!$this->account
    ->isAnonymous()) {

    // Check roles.
    foreach ($roles as $rid) {
      if (!empty($bypass_role[$rid])) {
        return FALSE;
      }
    }
  }
  $restrictedPages = $config
    ->get('pages_restriction');
  if (empty($restrictedPages)) {
    return FALSE;
  }
  $restrictedPages = explode(PHP_EOL, $restrictedPages);
  if (empty($this->request
    ->getRequestUri())) {
    return FALSE;
  }

  // Get current path.
  $currentPath = $this->currentPath
    ->getPath();
  $currentPath = $this->aliasManager
    ->getAliasByPath($currentPath);

  // Check for bypass on session.
  $pages_restriction_bypass = $this->session
    ->get('pages_restriction_bypass');

  // If user has bypass skip.
  if (!empty($pages_restriction_bypass) && in_array($currentPath, $pages_restriction_bypass)) {
    return FALSE;
  }
  $restrictedPaths = (array) $this->pagesRestrictionHelper
    ->getRestrictedPagesByConfig($restrictedPages);
  if (empty($restrictedPaths) || !in_array($currentPath, $restrictedPaths)) {
    return FALSE;
  }
  foreach ($restrictedPages as $restrictedPage) {
    if (empty($restrictedPage[0]) || empty($restrictedPage[1])) {
      continue;
    }
    $restrictedPage = explode('|', $restrictedPage);
    $restrictedPath = Xss::filter($restrictedPage[0]);
    $restrictedPath = trim($restrictedPath);
    if ($restrictedPath != $currentPath) {
      continue;
    }
    $targetPage = Xss::filter($restrictedPage[1]);
    $targetPage = trim($targetPage);
    if (!empty($config
      ->get('keep_parameters'))) {
      $queryParameters = $this->request->query
        ->all();
      $queryParameters = [
        'query' => $queryParameters,
      ];
      $targetPage = Url::fromUserInput($targetPage, $queryParameters)
        ->toString();
    }
    $response = new RedirectResponse($targetPage);
    $response
      ->send();
    $event
      ->stopPropagation();
    exit;
  }
}