From da80590036d6e55c5965fe3ade251948520cca64 Mon Sep 17 00:00:00 2001 From: Tim Otten Date: Mon, 24 Jul 2023 22:01:23 -0700 Subject: [PATCH] Civi\Core\Url - Allow dynamic variables --- Civi/Core/Url.php | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/Civi/Core/Url.php b/Civi/Core/Url.php index c521998975..6bd147f29f 100644 --- a/Civi/Core/Url.php +++ b/Civi/Core/Url.php @@ -108,6 +108,13 @@ final class Url implements \JsonSerializable { */ private $vars; + /** + * Define a dynamic lookup for variables. + * + * @var callable|null + */ + private $varsCallback; + /** * @param string $logicalUri * @param string|null $flags @@ -430,6 +437,27 @@ final class Url implements \JsonSerializable { return $this; } + /** + * @return callable|null + */ + public function getVarsCallback(): ?callable { + return $this->varsCallback; + } + + /** + * Configure dynamic lookup for variables. + * + * @param callable|null $varsCallback + * Function(string $varName): ?string + * Determine the string-value of the variable. (May be ''.) + * If the variable is unavailable, return NULL. + * @return $this + */ + public function setVarsCallback(?callable $varsCallback) { + $this->varsCallback = $varsCallback; + return $this; + } + /** * Apply a series of flags using short-hand notation. * @@ -553,7 +581,16 @@ final class Url implements \JsonSerializable { // Replace variables $result = preg_replace_callback('/\[(\w+)\]/', function($m) { $var = $m[1]; - return isset($this->vars[$var]) ? urlencode($this->vars[$var]) : "[$var]"; + if (isset($this->vars[$var])) { + return urlencode($this->vars[$var]); + } + if ($this->varsCallback !== NULL) { + $value = call_user_func($this->varsCallback, $var); + if ($value !== NULL) { + return urlencode($value); + } + } + return "[$var]"; }, $result); } -- 2.25.1