You are here

public function RequestSubscriber::onRequestCheckRedirect in Content Translation Redirect 8

Handles the redirect if any found.

Parameters

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

File

src/EventSubscriber/RequestSubscriber.php, line 81

Class

RequestSubscriber
Redirect subscriber for controller requests.

Namespace

Drupal\content_translation_redirect\EventSubscriber

Code

public function onRequestCheckRedirect(GetResponseEvent $event) {

  /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
  $entity = $this
    ->checkContentEntityCanonicalRoute();
  if ($entity && $entity
    ->isTranslatable()) {

    // Get current language and entity translation language.
    $current_language = $this->languageManager
      ->getCurrentLanguage(LanguageInterface::TYPE_CONTENT);
    $entity_language = $entity
      ->language();

    // Get redirect entity ID.
    $redirect_entity_id = $entity
      ->getEntityTypeId() . '__' . $entity
      ->bundle();

    // Check translation into current language.

    /** @var \Drupal\content_translation_redirect\ContentTranslationRedirectInterface $redirect_entity */
    if ($entity_language
      ->getId() != $current_language
      ->getId() && ($redirect_entity = $this->storage
      ->load($redirect_entity_id))) {

      // Get current path.
      $url = Url::fromRoute('<current>')
        ->setAbsolute();
      $current_path = $url
        ->toString();

      // Get redirect path to page in original language.
      $original_language = $entity
        ->getUntranslated()
        ->language();
      $url
        ->setOption('language', $original_language);
      $redirect_path = $url
        ->toString();

      // Redirect if the current path is not equal to the redirection path.
      if ($redirect_path != $current_path) {
        $status_code = $redirect_entity
          ->getStatusCode() ?: $this->config
          ->get('code');
        $message = $redirect_entity
          ->getMessage() ?: $this->config
          ->get('message');
        $response = new LocalRedirectResponse($redirect_path, $status_code);
        $response
          ->addCacheableDependency($url);
        $event
          ->setResponse($response);

        // Show warning message.
        if ($message) {

          // Get translated language name.
          $language_name = $this->languageManager
            ->getLanguageName($current_language
            ->getId());

          // Give the opportunity to display the name of the language
          // for which there is no translation.
          $message = new FormattableMarkup($message, [
            '%language' => $language_name,
          ]);
          $this
            ->messenger()
            ->addWarning($message);
        }
      }
    }
  }
}