diff --git a/src/Str/StringHelper.php b/src/Str/StringHelper.php index 832999c..10f85d5 100644 --- a/src/Str/StringHelper.php +++ b/src/Str/StringHelper.php @@ -11,6 +11,7 @@ use DateTime; use Exception; +use RuntimeException; use Stringable; use Toolkit\Stdlib\Arr; use Toolkit\Stdlib\Str\Traits\StringCaseHelperTrait; @@ -295,25 +296,29 @@ public static function replaces(string $tplCode, array $vars): string * Simple render vars to template string. * * @param string $tplCode - * @param array $vars - * @param string $format Template var format + * @param array $vars + * @param string $format Template var format + * @param bool $mustVar Must find var in $vars, otherwise throw exception * * @return string */ - public static function renderVars(string $tplCode, array $vars, string $format = '{{%s}}'): string + public static function renderVars(string $tplCode, array $vars, string $format = '{{%s}}', bool $mustVar = false): string { // get left chars - [$left, $right] = explode('%s', $format); + [$left, $right] = explode('%s', $format, 2); if (!$vars || !str_contains($tplCode, $left)) { return $tplCode; } $pattern = sprintf('/%s([\w\s.-]+)%s/', preg_quote($left, '/'), preg_quote($right, '/')); - return preg_replace_callback($pattern, static function (array $match) use ($vars) { + return preg_replace_callback($pattern, static function (array $match) use ($vars, $mustVar) { if ($var = trim($match[1])) { - $val = Arr::getByPath($vars, $var); - if ($val !== null) { - return is_array($val) ? Arr::toStringV2($val) : (string)$val; + $value = Arr::getByPath($vars, $var); + if ($value !== null) { + return is_array($value) ? Arr::toStringV2($value) : (string)$value; + } + if ($mustVar) { + throw new RuntimeException(sprintf('template var not found: %s', $var)); } } diff --git a/src/Str/Traits/StringCheckHelperTrait.php b/src/Str/Traits/StringCheckHelperTrait.php index d4282b7..e851933 100644 --- a/src/Str/Traits/StringCheckHelperTrait.php +++ b/src/Str/Traits/StringCheckHelperTrait.php @@ -478,6 +478,16 @@ public static function isVarName(string $string): bool return preg_match('@^[a-zA-Z_\x7f-\xff][a-zA-Z\d_\x7f-\xff]*$@i', $string) === 1; } + /** + * @param string $str + * + * @return bool + */ + public static function isAlpha(string $str): bool + { + return preg_match('/^[a-zA-Z]+$/', $str) === 1; + } + /** * @param string $str * diff --git a/test/Str/StringHelperTest.php b/test/Str/StringHelperTest.php index 9cf49d8..324bc8a 100644 --- a/test/Str/StringHelperTest.php +++ b/test/Str/StringHelperTest.php @@ -291,6 +291,13 @@ public function testRenderVars(): void $text = Str::renderVars('tags: ${ tags }', $vars, '${%s}'); $this->assertEquals('tags: [php, java]', $text); + + $vars = [ + 'company' => 'mycompany', + 'namePath' => 'group.demo1', + ]; + $text = Str::renderVars('java/com/{company}/{namePath}', $vars, '{%s}'); + $this->assertEquals('java/com/mycompany/group.demo1', $text); } public function testBeforeAfter(): void