You are here

public function NodeTranslationExceptionSubscriber::onException in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/node/src/EventSubscriber/NodeTranslationExceptionSubscriber.php \Drupal\node\EventSubscriber\NodeTranslationExceptionSubscriber::onException()
  2. 10 core/modules/node/src/EventSubscriber/NodeTranslationExceptionSubscriber.php \Drupal\node\EventSubscriber\NodeTranslationExceptionSubscriber::onException()

Redirects not found node translations using the key value collection.

Parameters

\Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event: The exception event.

File

core/modules/node/src/EventSubscriber/NodeTranslationExceptionSubscriber.php, line 86

Class

NodeTranslationExceptionSubscriber
Redirect node translations that have been consolidated by migration.

Namespace

Drupal\node\EventSubscriber

Code

public function onException(GetResponseForExceptionEvent $event) {
  $exception = $event
    ->getException();

  // If this is not a 404, we don't need to check for a redirection.
  if (!$exception instanceof NotFoundHttpException) {
    return;
  }
  $previous_exception = $exception
    ->getPrevious();
  if ($previous_exception instanceof ParamNotConvertedException) {
    $route_name = $previous_exception
      ->getRouteName();
    $parameters = $previous_exception
      ->getRawParameters();
    if ($route_name === 'entity.node.canonical' && isset($parameters['node'])) {

      // If the node_translation_redirect state is not set, we don't need to check
      // for a redirection.
      if (!$this->state
        ->get('node_translation_redirect')) {
        return;
      }
      $old_nid = $parameters['node'];
      $collection = $this->keyValue
        ->get('node_translation_redirect');
      if ($old_nid && ($value = $collection
        ->get($old_nid))) {
        list($nid, $langcode) = $value;
        $language = $this->languageManager
          ->getLanguage($langcode);
        $url = $this->urlGenerator
          ->generateFromRoute('entity.node.canonical', [
          'node' => $nid,
        ], [
          'language' => $language,
        ]);
        $response = new RedirectResponse($url, 301);
        $event
          ->setResponse($response);
      }
    }
  }
}