|
11 | 11 |
|
12 | 12 | use DateTime;
|
13 | 13 | use Exception;
|
| 14 | +use RuntimeException; |
14 | 15 | use Stringable;
|
15 | 16 | use Toolkit\Stdlib\Arr;
|
16 | 17 | use Toolkit\Stdlib\Str\Traits\StringCaseHelperTrait;
|
@@ -295,25 +296,29 @@ public static function replaces(string $tplCode, array $vars): string
|
295 | 296 | * Simple render vars to template string.
|
296 | 297 | *
|
297 | 298 | * @param string $tplCode
|
298 |
| - * @param array $vars |
299 |
| - * @param string $format Template var format |
| 299 | + * @param array $vars |
| 300 | + * @param string $format Template var format |
| 301 | + * @param bool $mustVar Must find var in $vars, otherwise throw exception |
300 | 302 | *
|
301 | 303 | * @return string
|
302 | 304 | */
|
303 |
| - public static function renderVars(string $tplCode, array $vars, string $format = '{{%s}}'): string |
| 305 | + public static function renderVars(string $tplCode, array $vars, string $format = '{{%s}}', bool $mustVar = false): string |
304 | 306 | {
|
305 | 307 | // get left chars
|
306 |
| - [$left, $right] = explode('%s', $format); |
| 308 | + [$left, $right] = explode('%s', $format, 2); |
307 | 309 | if (!$vars || !str_contains($tplCode, $left)) {
|
308 | 310 | return $tplCode;
|
309 | 311 | }
|
310 | 312 |
|
311 | 313 | $pattern = sprintf('/%s([\w\s.-]+)%s/', preg_quote($left, '/'), preg_quote($right, '/'));
|
312 |
| - return preg_replace_callback($pattern, static function (array $match) use ($vars) { |
| 314 | + return preg_replace_callback($pattern, static function (array $match) use ($vars, $mustVar) { |
313 | 315 | if ($var = trim($match[1])) {
|
314 |
| - $val = Arr::getByPath($vars, $var); |
315 |
| - if ($val !== null) { |
316 |
| - return is_array($val) ? Arr::toStringV2($val) : (string)$val; |
| 316 | + $value = Arr::getByPath($vars, $var); |
| 317 | + if ($value !== null) { |
| 318 | + return is_array($value) ? Arr::toStringV2($value) : (string)$value; |
| 319 | + } |
| 320 | + if ($mustVar) { |
| 321 | + throw new RuntimeException(sprintf('template var not found: %s', $var)); |
317 | 322 | }
|
318 | 323 | }
|
319 | 324 |
|
|
0 commit comments