From 6216a02fd074dd22b12cd8230aa5159a371823e7 Mon Sep 17 00:00:00 2001
From: Heissen Lopez <heissen.lopez@gmail.com>
Date: Mon, 30 Dec 2024 18:09:33 -0500
Subject: [PATCH] #3100507 Add support for external URL query parameter
 handling

The changes:\n- Add new parameter 'is_external' to UrlHelper::buildQuery() to handle external URLs differently\n- Modify query parameter handling in external URLs to remove empty query parameters\n- Update UnroutedUrlAssembler to use the new parameter when building external URLs
---
 core/lib/Drupal/Component/Utility/UrlHelper.php       | 7 +++++--
 core/lib/Drupal/Core/Utility/UnroutedUrlAssembler.php | 2 +-
 2 files changed, 6 insertions(+), 3 deletions(-)

diff --git a/core/lib/Drupal/Component/Utility/UrlHelper.php b/core/lib/Drupal/Component/Utility/UrlHelper.php
index 1f5cc9145c5e..70c59033d802 100644
--- a/core/lib/Drupal/Component/Utility/UrlHelper.php
+++ b/core/lib/Drupal/Component/Utility/UrlHelper.php
@@ -32,6 +32,9 @@ class UrlHelper {
    * @param string $parent
    *   (optional) Internal use only. Used to build the $query array key for
    *   nested items. Defaults to an empty string.
+   * @param string $is_external
+   *   (optional) Determine if the processing query is part of external link
+   *   and remove empty query parameters.
    *
    * @return string
    *   A string encoded with rawurlencode() which can be used as or appended to
@@ -39,7 +42,7 @@ class UrlHelper {
    *
    * @ingroup php_wrappers
    */
-  public static function buildQuery(array $query, $parent = '') {
+  public static function buildQuery(array $query, $parent = '', $is_external = FALSE) {
     $params = [];
 
     foreach ($query as $key => $value) {
@@ -50,7 +53,7 @@ public static function buildQuery(array $query, $parent = '') {
         $params[] = static::buildQuery($value, $key);
       }
       // If a query parameter value is NULL, only append its key.
-      elseif (!isset($value)) {
+      elseif (!isset($value)|| ($is_external && empty($value) && strlen($value) == 0)) {
         $params[] = $key;
       }
       else {
diff --git a/core/lib/Drupal/Core/Utility/UnroutedUrlAssembler.php b/core/lib/Drupal/Core/Utility/UnroutedUrlAssembler.php
index b4746186bf34..faffd35d2175 100644
--- a/core/lib/Drupal/Core/Utility/UnroutedUrlAssembler.php
+++ b/core/lib/Drupal/Core/Utility/UnroutedUrlAssembler.php
@@ -93,7 +93,7 @@ protected function buildExternalUrl($uri, array $options = [], $collect_bubbleab
     }
     // Append the query.
     if ($options['query']) {
-      $uri .= '?' . UrlHelper::buildQuery($options['query']);
+      $uri .= '?' . UrlHelper::buildQuery($options['query'], '', TRUE);
     }
     // Reassemble.
     $url = $uri . $options['fragment'];
-- 
GitLab