You are here

public function DomainRedirectEventSubscriber::requestHandler in Domain 301 Redirect 8

This method is called whenever the kernel.request event is dispatched.

@todo Needs a service which will handle the exclusion/inclusion of the mentioned path/page.

Parameters

\Symfony\Component\HttpKernel\Event\GetResponseEvent $event: The response event.

File

src/EventSubscriber/DomainRedirectEventSubscriber.php, line 102

Class

DomainRedirectEventSubscriber
Class DomainRedirectEventSubscriber.

Namespace

Drupal\domain_301_redirect\EventSubscriber

Code

public function requestHandler(GetResponseEvent $event) {

  // If domain redirection is not enabled, then no need to process further.
  if (!$this->config
    ->get('enabled')) {
    return;
  }

  // If user has 'bypass' permission, then no need to process further.
  if ($this->userAccount
    ->hasPermission('bypass domain 301 redirect')) {
    return;
  }

  // Check that the domain is set just to be safe.
  $domain = trim(trim($this->config
    ->get('domain')), '/');
  if (empty($domain)) {
    return;
  }

  // Check the path configuration to see if we should bypass redirection.
  if ($this
    ->checkPath()) {
    return;
  }

  // If domain doesn't contain http/https, then add those to domain.
  if (!preg_match('|^https?://|', $domain)) {
    $domain = 'http://' . $domain;
  }

  // Parse the domain to get various settings like port.
  $domain_parts = parse_url($domain);
  $parsed_domain = $domain_parts['host'];
  $parsed_domain .= !empty($domain_parts['port']) ? ':' . $domain_parts['port'] : '';
  $parsed_scheme = $domain_parts['scheme'];

  // If we're not on the same host, the user has access and this page isn't
  // an exception, redirect.
  $scheme = $this->request
    ->getScheme();
  $host = $this->request
    ->getHttpHost();
  if ($parsed_domain != $host || $parsed_scheme != $scheme) {
    $uri = $this->request
      ->getRequestUri();
    $response = new TrustedRedirectResponse($domain . $uri, 301);

    // Add the same header used by the redirect module, often used in Varnish.
    $response->headers
      ->add([
      'X-Redirect-ID' => 0,
    ]);

    // Add cache metadata to cache the response.
    $response
      ->addCacheableDependency(CacheableMetadata::createFromRenderArray([
      '#cache' => [
        'max-age' => Cache::PERMANENT,
        'contexts' => [
          'url',
          'user.permissions',
        ],
        'tags' => [
          'config:domain_301_redirect.settings',
        ],
      ],
    ]));
    $event
      ->setResponse($response);
  }
}