22
33namespace Tempest \View \Components ;
44
5- use Tempest \ Container \ Container ;
5+ use Stringable ;
66use Tempest \Core \AppConfig ;
7- use Tempest \View \Elements \ElementFactory ;
7+ use Tempest \Support \Str \ImmutableString ;
8+ use Tempest \Support \Str \MutableString ;
9+ use Tempest \View \Elements \CollectionElement ;
810use Tempest \View \Elements \ViewComponentElement ;
9- use Tempest \View \GenericView ;
1011use Tempest \View \Parser \TempestViewCompiler ;
1112use Tempest \View \Parser \Token ;
1213use Tempest \View \ViewComponent ;
1314use Tempest \View \ViewConfig ;
14- use Tempest \View \ ViewRenderer ;
15+ use function Tempest \Support \ arr ;
1516
1617final class DynamicViewComponent implements ViewComponent
1718{
@@ -36,27 +37,43 @@ public static function getName(): string
3637 public function compile (ViewComponentElement $ element ): string
3738 {
3839 $ name = $ this ->token ->getAttribute ('is ' ) ?? $ this ->token ->getAttribute (':is ' );
40+
3941 $ isExpression = $ this ->token ->getAttribute (':is ' ) !== null ;
4042
41- return sprintf (
42- '<?php eval( \'?> \' . \Tempest\get(%s::class)->render(%s, %s)); ?> ' ,
43- self ::class,
44- $ isExpression ? $ name : "' {$ name }' " ,
45- var_export ($ element ->getAttributes (), true ), // @mago-expect best-practices/no-debug-symbols
46- );
47- }
43+ $ collectionElement = new CollectionElement ($ element ->getChildren ());
4844
49- public function render (string $ name , array $ attributes ): string
50- {
51- $ viewComponent = $ this ->viewConfig ->viewComponents [$ name ] ?? null ;
45+ $ attributes = arr ($ element ->getAttributes ())
46+ ->filter (fn (string $ value , string $ key ) => $ key !== 'is ' && $ key !== ':is ' )
47+ ->map (function (string $ value , string $ key ) {
48+ return sprintf ('%s="%s" ' , $ key , trim ($ value ));
49+ })
50+ ->implode (' ' )
51+ ->when (
52+ fn (Stringable $ string ) => (string ) $ string !== '' ,
53+ fn (Stringable $ string ) => new ImmutableString (" {$ string }" ),
54+ );
5255
53- $ element = new ViewComponentElement (
54- environment: $ this ->appConfig ->environment ,
55- compiler: $ this ->compiler ,
56- viewComponent: $ viewComponent ,
57- attributes: $ attributes ,
56+ $ compiledChildren = sprintf (
57+ <<<'HTML'
58+ <%s%s>
59+ %s
60+ </%s>
61+ HTML,
62+ '%s ' ,
63+ $ attributes ,
64+ $ collectionElement ->compile (),
65+ '%s ' ,
5866 );
5967
60- return $ element ->compile ();
68+ $ compiled = sprintf (
69+ '<?php echo \Tempest\get(\Tempest\View\Renderers\TempestViewRenderer::class)->render(sprintf(<<< \'HTML \'
70+ %s
71+ HTML, %s, %s)); ?> ' ,
72+ $ compiledChildren ,
73+ $ isExpression ? $ name : "' {$ name }' " ,
74+ $ isExpression ? $ name : "' {$ name }' " ,
75+ );
76+ lw ($ compiled );
77+ return $ compiled ;
6178 }
6279}
0 commit comments