UrlTest - Add coverage for variable-substitution
authorTim Otten <totten@civicrm.org>
Tue, 25 Jul 2023 03:34:22 +0000 (20:34 -0700)
committerTim Otten <totten@civicrm.org>
Tue, 25 Jul 2023 05:29:36 +0000 (22:29 -0700)
Civi/Core/Url.php
tests/phpunit/Civi/Core/UrlTest.php

index 69ab20db081d9d65e7ddddf65b41fb9aad4c6922..c521998975051880b96faa44ffbfa9a8a46afc46 100644 (file)
@@ -426,7 +426,7 @@ final class Url implements \JsonSerializable {
    * @return $this
    */
   public function addVars(array $vars): Url {
-    $this->vars = array_merge($this->vars ?: [], $vars);
+    $this->vars = $vars + ($this->vars ?: []);
     return $this;
   }
 
index 2fdcc779d6834a3d5bd943069b62f7c2d5857000..c12933c13a6bccfd9f4d464a29b862eabff8d1f2 100644 (file)
@@ -127,4 +127,26 @@ class UrlTest extends \CiviUnitTestCase {
     }
   }
 
+  public function testVars(): void {
+    $vars = ['hi' => 'hello world?', 'contact' => 123];
+
+    $examples = [];
+    $examples[] = ['civicrm/admin/hello+world%3F', Civi::url('backend://civicrm/admin/[hi]?x=1')];
+    $examples[] = ['msg=hello+world%3F&id=123', Civi::url('backend://civicrm/admin?msg=[hi]&id=[contact]')];
+    $examples[] = ['a=123&b=456', Civi::url('backend://civicrm/admin?a=[1]&b=[2]')->addVars([1 => 123, 2 => 456])];
+    $examples[] = ['#/page?msg=hello+world%3F', Civi::url('backend://civicrm/a/#/page?msg=[hi]')];
+    $examples[] = ['a=hello+world%3F&b=Au+re%2Fvoir', Civi::url('frontend://civicrm/user?a=[hi]&b=[bye]')->addVars(['bye' => 'Au re/voir'])];
+    $examples[] = ['some_xyz=123', Civi::url('//civicrm/foo?some_[key]=123')->addVars(['key' => 'xyz'])];
+
+    // Unrecognized []'s are preserved as literals, which allows interop with deep form fields
+    $examples[] = ['some[key]=123', Civi::url('//civicrm/foo?some[key]=123')];
+
+    foreach ($examples as $key => $example) {
+      /** @var \Civi\Core\Url $url */
+      [$expected, $url] = $example;
+      $url->addVars($vars);
+      $this->assertStringContainsString($expected, (string) $url, sprintf("%s at %d should be have matching output", __FUNCTION__, $key));
+    }
+  }
+
 }