Skip to content

Commit b481bf8

Browse files
WIP SKETCH: Add support for callable components
We’ll use this for Codex-PHP integration. TODO: The callable component also needs access to the component node’s children (e.g. the “text” in <cdx-button>text</cdx-button>.
1 parent 3b1c386 commit b481bf8

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

src/App.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ class App {
2121
/** @var (Component|string|callable)[] */
2222
private $components = [];
2323

24+
private $callableComponents = [];
25+
2426
/**
2527
* @param callable[] $methods The available methods.
2628
* The key is the method name, the value is the corresponding callable.
@@ -42,6 +44,10 @@ public function registerComponentTemplate( string $name, $template ): void {
4244
$this->components[$name] = $template;
4345
}
4446

47+
public function registerComponentCallable( string $name, callable $callable ): void {
48+
$this->callableComponents[$name] = $callable;
49+
}
50+
4551
public function evaluateExpression( string $expression, array $data ) {
4652
return $this->expressionParser->parse( $expression )
4753
->evaluate( $data );
@@ -53,6 +59,12 @@ public function renderComponent( string $componentName, array $data ): string {
5359
}
5460

5561
public function renderComponentToDOM( string $componentName, array $data ): DOMElement {
62+
$callableComponent = $this->callableComponents[$componentName] ?? null;
63+
if ( $callableComponent !== null ) {
64+
$html = $callableComponent( $data );
65+
$document = $this->htmlParser->parseHtml( $html );
66+
return $this->htmlParser->getRootNode( $document );
67+
}
5668
return $this->getComponent( $componentName )
5769
->render( $data );
5870
}

tests/php/AppTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,4 +49,14 @@ public function testNestedComponents(): void {
4949
$this->assertSame( '<div><p><span>text</span></p></div>', $result );
5050
}
5151

52+
public function testCallableComponent(): void {
53+
$app = new App( [] );
54+
$app->registerComponentTemplate( 'root', '<div><x-a :a="rootVar"></x-a></div>' );
55+
$app->registerComponentCallable( 'x-a', fn ( $data ) => '<p>' . strtoupper( $data['a'] ) . '</p>' );
56+
57+
$result = $app->renderComponent( 'root', [ 'rootVar' => 'text' ] );
58+
59+
$this->assertSame( '<div><p>TEXT</p></div>', $result );
60+
}
61+
5262
}

0 commit comments

Comments
 (0)