domainConfig = $config_factory->get('redirect_domain.domains'); $this->redirectConfig = $config_factory->get('redirect.settings'); $this->redirectChecker = $redirect_checker; $this->pathMatcher = $path_matcher; } /** * Handles the domain redirect if any found. * * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event * The event to process. */ 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; // Checks if there is a redirect domain in the configuration. if (isset($domains[str_replace('.', ':', $host)])) { foreach ($domains[str_replace('.', ':', $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; } } } } /** * Prior to set the response it check if we can redirect. * * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event * The event object. * @param \Drupal\Core\Url $url * The Url where we want to redirect. */ protected function setResponse(GetResponseEvent $event, Url $url) { $request = $event->getRequest(); parse_str($request->getQueryString(), $query); $url->setOption('query', $query); $url->setAbsolute(TRUE); } /** * {@inheritdoc} */ public static function getSubscribedEvents() { // This needs to run before RouterListener::onKernelRequest(), which has // a priority of 32 and // RedirectRequestSubscriber::onKernelRequestCheckRedirect(), which has // a priority of 33. Otherwise, that aborts the request if no matching // route is found. $events[KernelEvents::REQUEST][] = ['onKernelRequestCheckDomainRedirect', 34]; return $events; } }