You are here

public function HttpsWwwRedirectSubscriber::redirect in HTTPS and WWW Redirect 2.x

Same name and namespace in other branches
  1. 8 src/EventSubscriber/HttpsWwwRedirectSubscriber.php \Drupal\httpswww\EventSubscriber\HttpsWwwRedirectSubscriber::redirect()

Executes a redirect if one is needed based on config.

Parameters

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

File

src/EventSubscriber/HttpsWwwRedirectSubscriber.php, line 54

Class

HttpsWwwRedirectSubscriber
Class HttpsWwwRedirectSubscriber.

Namespace

Drupal\httpswww\EventSubscriber

Code

public function redirect(GetResponseEvent $event) {

  // Quit if it's not enabled.
  if (empty($this->config
    ->get('enabled'))) {
    return;
  }

  // Quit if the user has the bypass permission.
  if ($this->account
    ->hasPermission('bypass httpswww redirect')) {
    return;
  }
  $host = $event
    ->getRequest()
    ->getHost();
  $scheme = $event
    ->getRequest()
    ->getScheme();
  $conf_scheme = $this->config
    ->get('scheme') ?: 'mixed';
  $use_prefix = $this->config
    ->get('prefix') == 'yes';
  $curr_url = $event
    ->getRequest()
    ->getSchemeAndHttpHost();

  // Set scheme.
  $new_url = ($conf_scheme === 'mixed' ? $scheme : $conf_scheme) . '://';

  // Set/remove prefix and add host.
  if ($use_prefix && substr($host, 0, 4) !== 'www.') {
    $new_url .= 'www.' . $host;
  }
  elseif (!$use_prefix && substr($host, 0, 4) === 'www.') {
    $new_url .= substr($host, 4);
  }
  else {
    $new_url .= $host;
  }

  // Check if the URL is valid and redirect if URLs doesn't match.
  if (UrlHelper::isValid($new_url, TRUE) && $curr_url !== $new_url) {
    $new_url .= $event
      ->getRequest()
      ->getRequestUri();
    $response = new TrustedRedirectResponse($new_url, 301);
    $build = [
      '#cache' => [
        'max-age' => 0,
        'contexts' => [
          'url',
          'user.permissions',
        ],
        'tags' => [
          'config:httpswww.settings',
        ],
      ],
    ];
    $cache_meta = CacheableMetadata::createFromRenderArray($build);
    $response
      ->addCacheableDependency($cache_meta);
    $event
      ->setResponse($response);
  }
}