Skip to content

Commit 5f35707

Browse files
SKETCH: Support sub-components
This is a bit odd in that Component doesn’t even know which components are registered in the app; sub-component handling is triggered iff the tag name contains a hyphen. I think this is reasonable, but we might still end up changing it. Completely untested so far.
1 parent cc8d926 commit 5f35707

File tree

1 file changed

+29
-4
lines changed

1 file changed

+29
-4
lines changed

src/Component.php

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -54,11 +54,13 @@ private function handleNode( DOMNode $node, array $data ) {
5454
$this->handleRawHtml( $node, $data );
5555

5656
if ( !$this->isRemovedFromTheDom( $node ) ) {
57-
$this->handleAttributeBinding( $node, $data );
58-
$this->handleIf( $node->childNodes, $data );
57+
if ( !$this->handleComponent( $node, $data ) ) {
58+
$this->handleAttributeBinding( $node, $data );
59+
$this->handleIf( $node->childNodes, $data );
5960

60-
foreach ( iterator_to_array( $node->childNodes ) as $childNode ) {
61-
$this->handleNode( $childNode, $data );
61+
foreach ( iterator_to_array( $node->childNodes ) as $childNode ) {
62+
$this->handleNode( $childNode, $data );
63+
}
6264
}
6365
}
6466
}
@@ -100,6 +102,29 @@ private function replaceMustacheVariables( DOMNode $node, array $data ) {
100102
}
101103
}
102104

105+
/** @return bool true if it was a component, false otherwise */
106+
private function handleComponent( DOMElement $node, array $data ): bool {
107+
if ( strpos( $node->tagName, '-' ) === false ) {
108+
return false;
109+
}
110+
$componentName = $node->tagName;
111+
112+
$componentData = [];
113+
foreach ( $node->attributes as $attribute ) {
114+
if ( str_starts_with( $attribute->name, ':' ) ) { // TODO PHP 8; TODO also v-bind: ?
115+
$name = substr( $attribute->name, 1 );
116+
$value = $this->app->evaluateExpression( $attribute->value, $data );
117+
} else {
118+
$name = $attribute->name;
119+
$value = $attribute->value;
120+
}
121+
$componentData[$name] = $value;
122+
}
123+
$rendered = $this->app->renderComponent( $componentName, $componentData );
124+
$node->replaceWith( $node->ownerDocument->adoptNode( $rendered ) );
125+
return true;
126+
}
127+
103128
private function handleAttributeBinding( DOMElement $node, array $data ) {
104129
/** @var DOMAttr $attribute */
105130
foreach ( iterator_to_array( $node->attributes ) as $attribute ) {

0 commit comments

Comments
 (0)