HttpsWwwRedirectSubscriber.php in HTTPS and WWW Redirect 8
File
src/EventSubscriber/HttpsWwwRedirectSubscriber.php
View source
<?php
namespace Drupal\httpswww\EventSubscriber;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Routing\TrustedRedirectResponse;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class HttpsWwwRedirectSubscriber implements EventSubscriberInterface {
protected $config;
protected $account;
public function __construct(ConfigFactoryInterface $config_factory, AccountInterface $account) {
$this->config = $config_factory
->get('httpswww.settings');
$this->account = $account;
}
public function redirect(GetResponseEvent $event) {
if (empty($this->config
->get('enabled'))) {
return;
}
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();
$new_url = ($conf_scheme === 'mixed' ? $scheme : $conf_scheme) . '://';
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;
}
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);
}
}
public static function getSubscribedEvents() {
$events[KernelEvents::REQUEST][] = [
'redirect',
299,
];
return $events;
}
}