function NodeTranslationExceptionSubscriber::onException

Same name in other branches
  1. 8.9.x 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()
  3. 11.x 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\ExceptionEvent $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(ExceptionEvent $event) {
    $exception = $event->getThrowable();
    // 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))) {
                [
                    $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);
            }
        }
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.