Skip to content

Commit 651173f

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 5b6318a commit 651173f

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

src/App.php

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

24+
/** @var callable[] */
25+
private $callableComponents = [];
26+
2427
private $componentSetups = [];
2528

2629
/**
@@ -51,6 +54,10 @@ public function registerComponentTemplate( string $name, $template, ?callable $s
5154
}
5255
}
5356

57+
public function registerComponentCallable( string $name, callable $callable ): void {
58+
$this->callableComponents[$name] = $callable;
59+
}
60+
5461
public function evaluateExpression( string $expression, array $data ) {
5562
return $this->expressionParser->parse( $expression )
5663
->evaluate( $data );
@@ -66,6 +73,14 @@ public function renderComponentToDOM( string $componentName, array $data ): DOME
6673
if ( $setup !== null ) {
6774
$data = $setup( $data );
6875
}
76+
77+
$callableComponent = $this->callableComponents[$componentName] ?? null;
78+
if ( $callableComponent !== null ) {
79+
$html = $callableComponent( $data );
80+
$document = $this->htmlParser->parseHtml( $html );
81+
return $this->htmlParser->getRootNode( $document );
82+
}
83+
6984
return $this->getComponent( $componentName )
7085
->render( $data );
7186
}

tests/php/AppTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,4 +146,14 @@ public function testComputedProperties(): void {
146146
$this->assertSame( $expected, $result );
147147
}
148148

149+
public function testCallableComponent(): void {
150+
$app = new App( [] );
151+
$app->registerComponentTemplate( 'root', '<div><x-a :a="rootVar"></x-a></div>' );
152+
$app->registerComponentCallable( 'x-a', fn ( $data ) => '<p>' . strtoupper( $data['a'] ) . '</p>' );
153+
154+
$result = $app->renderComponent( 'root', [ 'rootVar' => 'text' ] );
155+
156+
$this->assertSame( '<div><p>TEXT</p></div>', $result );
157+
}
158+
149159
}

0 commit comments

Comments
 (0)