Skip to content

Commit

Permalink
Feat: Normalize template name using regex to allow capitalized prefixes
Browse files Browse the repository at this point in the history
  * 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
  • Loading branch information
literat committed Jun 12, 2024
1 parent 724bfcb commit d9ebece
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

<!-- There should always be "Unreleased" section at the beginning. -->
## 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
Expand Down
15 changes: 14 additions & 1 deletion src/Compiler/ComponentTagCompiler.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
);
}

/**
Expand Down Expand Up @@ -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) {
Expand Down
7 changes: 7 additions & 0 deletions tests/Compiler/ComponentTagCompilerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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('<UNSTABLE_Alert color="primary" />', 'alias');

$this->assertSame('{% embed "@alias/unstable_Alert.twig" with { props: {\'color\': "primary"} } %}{% endembed %}', $compiler->compile());
}

public function testShouldCompileClosingTag(): void
{
$compiler = new ComponentTagCompiler('<Alert color="primary">test</Alert>', 'alias');
Expand Down

0 comments on commit d9ebece

Please sign in to comment.