From d9ebece69cdbf01da4a4f4f33872e564a0f2a35f Mon Sep 17 00:00:00 2001 From: literat Date: Wed, 12 Jun 2024 10:13:43 +0200 Subject: [PATCH] Feat: Normalize template name using regex to allow capitalized prefixes * prefixes in format `PREFIX_` for template name can now be used * it will normalize the template name to lower case - `prefix_` * motivation is to allowed `UNSTABLE_` prefix name for our components --- CHANGELOG.md | 1 + src/Compiler/ComponentTagCompiler.php | 15 ++++++++++++++- tests/Compiler/ComponentTagCompilerTest.php | 7 +++++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9567251..d5ff9d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- Feat: Normalize template name using regex to allow capitalized prefixes ## 3.2.1 - 2023-03-30 - Fix: Negative lookahead breaks parsing of element closing bracket diff --git a/src/Compiler/ComponentTagCompiler.php b/src/Compiler/ComponentTagCompiler.php index 4cf62f2..97e3c14 100644 --- a/src/Compiler/ComponentTagCompiler.php +++ b/src/Compiler/ComponentTagCompiler.php @@ -83,7 +83,13 @@ function (array $matches) { protected function componentStartString(string $component, string $attributes): string { - return "{% embed \"@" . $this->twigPathAlias . "/" . lcfirst($component) . ".twig\" with { props: $attributes } %}"; + return sprintf( + // another `%` is used for escaping the `%`, e. g. `%%` -> `%` + "{%% embed \"@%s/%s.twig\" with { props: %s } %%}", + $this->twigPathAlias, + $this->normalizeComponentPathName($component), + $attributes + ); } /** @@ -146,6 +152,13 @@ function (array $matches) { ); } + private function normalizeComponentPathName(string $name): string + { + return preg_replace_callback('/^[A-Z]+_?/', function ($matches) { + return strtolower($matches[0]); + }, $name) ?: $name; + } + private function valueParser(?string $value, string $attribute): string { if ($value === null) { diff --git a/tests/Compiler/ComponentTagCompilerTest.php b/tests/Compiler/ComponentTagCompilerTest.php index 346e459..bb86fa3 100644 --- a/tests/Compiler/ComponentTagCompilerTest.php +++ b/tests/Compiler/ComponentTagCompilerTest.php @@ -15,6 +15,13 @@ public function testShouldCompile(): void $this->assertSame('{% embed "@alias/alert.twig" with { props: {\'color\': "primary"} } %}{% endembed %}', $compiler->compile()); } + public function testShouldCompileUnstable(): void + { + $compiler = new ComponentTagCompiler('', 'alias'); + + $this->assertSame('{% embed "@alias/unstable_Alert.twig" with { props: {\'color\': "primary"} } %}{% endembed %}', $compiler->compile()); + } + public function testShouldCompileClosingTag(): void { $compiler = new ComponentTagCompiler('test', 'alias');