From d65ecc5031947462b9862c117f6ca141dba073b5 Mon Sep 17 00:00:00 2001 From: Tim Otten Date: Thu, 20 Jul 2023 22:20:41 -0700 Subject: [PATCH] Civi::url() - Add support for vars --- Civi.php | 4 ++++ Civi/Core/Url.php | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/Civi.php b/Civi.php index 83a264cb94..c2a025d38e 100644 --- a/Civi.php +++ b/Civi.php @@ -247,6 +247,10 @@ class Civi { * Ex: Link to a static asset (resource-file) in an extension. * $url = Civi::url('ext://org.civicrm.search_kit/css/crmSearchTasks.css'); * + * Ex: Link with variable substitution + * $url = Civi::url('frontend://civicrm/ajax/api4/[entity]/[action]') + * ->addVars(['entity' => 'Foo', 'action' => 'bar']); + * * NOTE: CiviCRM is integrated into many environments, and they handle URL-construction different ways. * For example, in Joomla+WordPress, there are separate sub-applications for the public-facing * frontend UI (`/`) and the staff-facing backend UI (`/wp-admin/` or `/administrator/`) -- each follows diff --git a/Civi/Core/Url.php b/Civi/Core/Url.php index 5bcb72dc5f..6e9a1e0a47 100644 --- a/Civi/Core/Url.php +++ b/Civi/Core/Url.php @@ -64,6 +64,13 @@ final class Url { */ private $ssl = NULL; + /** + * List of values to mix-in to the final/rendered URL. + * + * @var string[]|null + */ + private $vars; + /** * @param string $logicalUri * @param string|null $flags @@ -237,6 +244,31 @@ final class Url { return $this; } + /** + * @return string[]|null + */ + public function getVars(): ?array { + return $this->vars; + } + + /** + * @param string[]|null $vars + */ + public function setVars(?array $vars): Url { + $this->vars = $vars; + return $this; + } + + /** + * @param string[] $vars + * + * @return $this + */ + public function addVars(array $vars): Url { + $this->vars = array_merge($this->vars ?: [], $vars); + return $this; + } + /** * @param string $flags * A series of flag-letters. Any of the following: @@ -339,6 +371,14 @@ final class Url { $result = 'http:' . substr($result, 6); } + if ($this->vars !== NULL) { + // Replace variables + $result = preg_replace_callback('/\[(\w+)\]/', function($m) { + $var = $m[1]; + return isset($this->vars[$var]) ? urlencode($this->vars[$var]) : "[$var]"; + }, $result); + } + return $this->htmlEscape ? htmlentities($result) : $result; } -- 2.25.1