You are here

public function DisabledLanguagesEventSubscriber::checkForDisabledLanguageAndRedirect in Disable language 8

File

src/EventSubscriber/DisabledLanguagesEventSubscriber.php, line 98

Class

DisabledLanguagesEventSubscriber
Subscribe to KernelEvents::REQUEST events.

Namespace

Drupal\disable_language\EventSubscriber

Code

public function checkForDisabledLanguageAndRedirect(GetResponseEvent $event) {

  // Do not redirect if this is a file.
  $params = $event
    ->getRequest()->attributes
    ->all();
  if (isset($params['scheme']) && in_array($params['scheme'], $this->schemes)) {
    return;
  }
  elseif ($this
    ->isPathExcluded()) {
    return;
  }
  elseif (!$this->currentUser
    ->hasPermission('view disabled languages')) {
    if ($this->disableLanguageManager
      ->isCurrentLanguageDisabled()) {

      // Get the configured redirect language if there is one.
      $redirect_language = $this->disableLanguageManager
        ->getFallbackLanguage();
      if ($redirect_language) {
        $language = \Drupal::languageManager()
          ->getLanguage($redirect_language);
      }
      else {
        $language = $this->disableLanguageManager
          ->getFirstEnabledLanguage();
      }
      if (isset($language)) {

        // Create url object to redirect to in the correct language. By
        // default we redirect to the frontpage.
        $url = Url::fromRoute('<front>', [], [
          'language' => $language,
        ]);

        // Check our configuration to see which routes should redirect to the
        // current page but in the correct language instead of the frontpage.
        $redirectOverrideRoutes = $this->config
          ->get('redirect_override_routes');
        if (!empty($redirectOverrideRoutes)) {
          $routeMatch = RouteMatch::createFromRequest($event
            ->getRequest());
          $routeName = $routeMatch
            ->getRouteName();
          if (in_array($routeName, $redirectOverrideRoutes)) {
            $url = Url::fromRoute($routeMatch
              ->getRouteName(), $routeMatch
              ->getRawParameters()
              ->all(), [
              'language' => $language,
              'query' => $event
                ->getRequest()->query
                ->all(),
            ]);
          }
        }

        // Set the response.
        $cache = new CacheableMetadata();
        $cache
          ->addCacheContexts([
          'languages',
          'url',
          'user.permissions',
        ]);
        $cache
          ->addCacheableDependency($this->config);
        $cache
          ->addCacheableDependency($language);
        $response = new TrustedRedirectResponse($url
          ->toString(), '307');
        $response
          ->addCacheableDependency($cache);
        $event
          ->setResponse($response);
      }
    }
  }
}