Skip to content

Commit 12b5503

Browse files
authored
feat(view): view components by file name (#1013)
1 parent 573d557 commit 12b5503

File tree

4 files changed

+26
-10
lines changed

4 files changed

+26
-10
lines changed

src/Tempest/View/src/ViewComponentDiscovery.php

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
use Tempest\Reflection\ClassReflector;
1212
use Tempest\View\Components\AnonymousViewComponent;
1313

14+
use function Tempest\Support\str;
15+
1416
final class ViewComponentDiscovery implements Discovery, DiscoversPath
1517
{
1618
use IsDiscovery;
@@ -42,19 +44,25 @@ public function discoverPath(DiscoveryLocation $location, string $path): void
4244
return;
4345
}
4446

45-
$content = ltrim(file_get_contents($path));
47+
$fileName = str(pathinfo($path, PATHINFO_FILENAME))->before('.');
48+
49+
$contents = str(file_get_contents($path))->ltrim();
50+
51+
$matches = $contents->match('/(?<header>(.|\n)*?)<x-component\s+name="(?<name>[\w\-]+)">(?<view>(.|\n)*?)<\/x-component>/');
52+
53+
if ($fileName->startsWith('x-')) {
54+
$this->discoveryItems->add($location, [
55+
$fileName->toString(),
56+
new AnonymousViewComponent(
57+
contents: $matches['view'] ?? $contents->toString(),
58+
file: $path,
59+
),
60+
]);
4661

47-
if (! str_contains($content, '<x-component name=')) {
4862
return;
4963
}
5064

51-
preg_match(
52-
pattern: '/(?<header>(.|\n)*?)<x-component name="(?<name>[\w\-]+)">(?<view>(.|\n)*?)<\/x-component>/',
53-
subject: $content,
54-
matches: $matches,
55-
);
56-
57-
if (! $matches['name']) {
65+
if (! isset($matches['name'], $matches['header'])) {
5866
return;
5967
}
6068

File renamed without changes.
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
<div>hi!</div>

tests/Integration/View/ViewComponentTest.php

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -405,7 +405,7 @@ public function test_view_component_with_camelcase_attribute(): void
405405

406406
public function test_php_code_in_attribute(): void
407407
{
408-
$html = $this->render(view(__DIR__ . '/../../Fixtures/Views/x-button-usage.view.php'));
408+
$html = $this->render(view(__DIR__ . '/../../Fixtures/Views/button-usage.view.php'));
409409

410410
$this->assertStringContainsString('/docs/', $html);
411411
}
@@ -588,4 +588,11 @@ public function test_attributes_variable_in_view_component(): void
588588
<div class="foo baz" style="font-weight: bold; text-decoration: underline;"></div>
589589
HTML, $html);
590590
}
591+
592+
public function test_file_name_component(): void
593+
{
594+
$html = $this->render('<x-file-component></x-file-component>');
595+
596+
$this->assertSame('<div>hi!</div>', $html);
597+
}
591598
}

0 commit comments

Comments
 (0)