You are here

public function DomainRedirectRequestSubscriber::onKernelRequestCheckDomainRedirect in Redirect 8

Handles the domain redirect if any found.

Parameters

\Symfony\Component\HttpKernel\Event\GetResponseEvent $event: The event to process.

File

modules/redirect_domain/src/EventSubscriber/DomainRedirectRequestSubscriber.php, line 68

Class

DomainRedirectRequestSubscriber
Redirect subscriber for controller requests.

Namespace

Drupal\redirect_domain\EventSubscriber

Code

public function onKernelRequestCheckDomainRedirect(GetResponseEvent $event) {
  $request = clone $event
    ->getRequest();
  if (!$this->redirectChecker
    ->canRedirect($request)) {
    return;
  }

  // Redirect between domains configuration.
  $domains = $this->domainConfig
    ->get('domain_redirects');
  if (!empty($domains)) {
    $host = $request
      ->getHost();
    $path = $request
      ->getPathInfo();
    $protocol = $request
      ->getScheme() . '://';
    $destination = NULL;

    // Prior to being saved the source domain value has any periods replaced
    // with a colon, which makes it suitable for use as a key. In order to
    // match against those values the current hostname must be similarly
    // converted.
    // @see \Drupal\redirect_domain\Form\RedirectDomainForm::submitForm()
    $converted_host = str_replace('.', ':', $host);

    // Checks if there is a redirect domain in the configuration.
    if (isset($domains[$converted_host])) {
      foreach ($domains[$converted_host] as $item) {
        if ($this->pathMatcher
          ->matchPath($path, $item['sub_path'])) {
          $destination = $item['destination'];
          break;
        }
      }
      if ($destination) {

        // Use the default status code from Redirect.
        $response = new TrustedRedirectResponse($protocol . $destination, $this->redirectConfig
          ->get('default_status_code'));
        $event
          ->setResponse($response);
        return;
      }
    }
  }
}