From 8a7ec235f5e832c92eda8e5ed7505d1f570832b5 Mon Sep 17 00:00:00 2001 From: pookmish Date: Thu, 20 Jan 2022 15:49:42 -0800 Subject: [PATCH] Modify the imported redirects to point at the node instead of the alias (#168) --- stanford_profile_helper.module | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/stanford_profile_helper.module b/stanford_profile_helper.module index 8ca54cc1..2096acfc 100644 --- a/stanford_profile_helper.module +++ b/stanford_profile_helper.module @@ -45,6 +45,26 @@ function stanford_profile_helper_form_taxonomy_overview_terms_alter(&$form, Form } } +/** + * Implements hook_ENTITY_TYPE_presave(). + */ +function stanford_profile_helper_redirect_presave(EntityInterface $redirect) { + $destination = $redirect->get('redirect_redirect')->getString(); + + // If a redirect is added to go to the aliased path of a node (often from + // importing redirect), change the destination to target the node instead. + // This works if the destination is `/about` or `/node/9`. + if (preg_match('/^internal:(\/.*)/', $destination, $matches)) { + // Find the internal path from the alias. + $path = \Drupal::service('path_alias.manager')->getPathByAlias($matches[1]); + + // Grab the node id from the internal path and use that as the destination. + if (preg_match('/node\/(\d+)/', $path, $matches)) { + $redirect->set('redirect_redirect', 'entity:node/' . $matches[1]); + } + } +} + /** * Implements hook_search_api_index_items_alter(). */