Skip to content

Commit 4ae8f02

Browse files
committed
Civi::url() - Add support for vars
1 parent da87f10 commit 4ae8f02

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

Civi.php

+4
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,10 @@ public static function settings($domainID = NULL) {
247247
* Ex: Link to a static asset (resource-file) in an extension.
248248
* $url = Civi::url('ext://org.civicrm.search_kit/css/crmSearchTasks.css');
249249
*
250+
* Ex: Link with variable substitution
251+
* $url = Civi::url('frontend://civicrm/ajax/api4/[entity]/[action]')
252+
* ->addVars(['entity' => 'Foo', 'action' => 'bar']);
253+
*
250254
* NOTE: CiviCRM is integrated into many environments, and they handle URL-construction different ways.
251255
* For example, in Joomla+WordPress, there are separate sub-applications for the public-facing
252256
* frontend UI (`/`) and the staff-facing backend UI (`/wp-admin/` or `/administrator/`) -- each follows

Civi/Core/Url.php

+40
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,13 @@ final class Url {
6464
*/
6565
private $ssl = NULL;
6666

67+
/**
68+
* List of values to mix-in to the final/rendered URL.
69+
*
70+
* @var string[]|null
71+
*/
72+
private $vars;
73+
6774
/**
6875
* @param string $logicalUri
6976
* @param string|null $flags
@@ -237,6 +244,31 @@ public function setSsl(?bool $ssl): Url {
237244
return $this;
238245
}
239246

247+
/**
248+
* @return string[]|null
249+
*/
250+
public function getVars(): ?array {
251+
return $this->vars;
252+
}
253+
254+
/**
255+
* @param string[]|null $vars
256+
*/
257+
public function setVars(?array $vars): Url {
258+
$this->vars = $vars;
259+
return $this;
260+
}
261+
262+
/**
263+
* @param string[] $vars
264+
*
265+
* @return $this
266+
*/
267+
public function addVars(array $vars): Url {
268+
$this->vars = array_merge($this->vars ?: [], $vars);
269+
return $this;
270+
}
271+
240272
/**
241273
* @param string $flags
242274
* A series of flag-letters. Any of the following:
@@ -339,6 +371,14 @@ public function __toString(): string {
339371
$result = 'http:' . substr($result, 6);
340372
}
341373

374+
if ($this->vars !== NULL) {
375+
// Replace variables
376+
$result = preg_replace_callback('/\[(\w+)\]/', function($m) {
377+
$var = $m[1];
378+
return isset($this->vars[$var]) ? urlencode($this->vars[$var]) : "[$var]";
379+
}, $result);
380+
}
381+
342382
return $this->htmlEscape ? htmlentities($result) : $result;
343383
}
344384

0 commit comments

Comments
 (0)