@@ -21,6 +21,8 @@ class App {
21
21
/** @var (Component|string|callable)[] */
22
22
private $ components = [];
23
23
24
+ private $ componentSetups = [];
25
+
24
26
/**
25
27
* @param callable[] $methods The available methods.
26
28
* The key is the method name, the value is the corresponding callable.
@@ -36,10 +38,17 @@ public function __construct( array $methods ) {
36
38
* @param string $name The component name.
37
39
* @param string|callable $template Either the template HTML as a string,
38
40
* or a callable that will return the template HTML as a string when called with no arguments.
41
+ * @param callable|null $setup An optional setup function.
42
+ * If set, the callable is called with the array of data used to render the component,
43
+ * and whichever array it returns is then used to actually render the template.
44
+ * This can be used, for example, to add additional data (the equivalent of `computed` in JS).
39
45
* @return void
40
46
*/
41
- public function registerComponentTemplate ( string $ name , $ template ): void {
47
+ public function registerComponentTemplate ( string $ name , $ template, ? callable $ setup = null ): void {
42
48
$ this ->components [$ name ] = $ template ;
49
+ if ( $ setup !== null ) {
50
+ $ this ->componentSetups [$ name ] = $ setup ;
51
+ }
43
52
}
44
53
45
54
public function evaluateExpression ( string $ expression , array $ data ) {
@@ -53,6 +62,10 @@ public function renderComponent( string $componentName, array $data ): string {
53
62
}
54
63
55
64
public function renderComponentToDOM ( string $ componentName , array $ data ): DOMElement {
65
+ $ setup = $ this ->componentSetups [$ componentName ] ?? null ;
66
+ if ( $ setup !== null ) {
67
+ $ data = $ setup ( $ data );
68
+ }
56
69
return $ this ->getComponent ( $ componentName )
57
70
->render ( $ data );
58
71
}
0 commit comments