|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Tempest\View\Components; |
| 4 | + |
| 5 | +use Tempest\Container\Container; |
| 6 | +use Tempest\Core\AppConfig; |
| 7 | +use Tempest\View\Elements\ElementFactory; |
| 8 | +use Tempest\View\Elements\ViewComponentElement; |
| 9 | +use Tempest\View\GenericView; |
| 10 | +use Tempest\View\Parser\TempestViewCompiler; |
| 11 | +use Tempest\View\Parser\Token; |
| 12 | +use Tempest\View\ViewComponent; |
| 13 | +use Tempest\View\ViewConfig; |
| 14 | +use Tempest\View\ViewRenderer; |
| 15 | + |
| 16 | +final class DynamicViewComponent implements ViewComponent |
| 17 | +{ |
| 18 | + private Token $token; |
| 19 | + |
| 20 | + public function __construct( |
| 21 | + private AppConfig $appConfig, |
| 22 | + private TempestViewCompiler $compiler, |
| 23 | + private ElementFactory $elementFactory, |
| 24 | + private ViewConfig $viewConfig, |
| 25 | + ) {} |
| 26 | + |
| 27 | + public function setToken(Token $token): void |
| 28 | + { |
| 29 | + $this->token = $token; |
| 30 | + } |
| 31 | + |
| 32 | + public static function getName(): string |
| 33 | + { |
| 34 | + return 'x-dynamic-component'; |
| 35 | + } |
| 36 | + |
| 37 | + public function compile(ViewComponentElement $element): string |
| 38 | + { |
| 39 | + $name = $this->token->getAttribute('is') ?? $this->token->getAttribute(':is'); |
| 40 | + $isExpression = $this->token->getAttribute(':is') !== null; |
| 41 | + |
| 42 | + return sprintf( |
| 43 | + '<?php eval(\'?>\' . \Tempest\get(%s::class)->render(%s, %s)); ?>', |
| 44 | + self::class, |
| 45 | + $isExpression ? $name : "'{$name}'", |
| 46 | + var_export($element->getAttributes(), true), // @mago-expect best-practices/no-debug-symbols |
| 47 | + ); |
| 48 | + } |
| 49 | + |
| 50 | + public function render(string $name, array $attributes): string |
| 51 | + { |
| 52 | + $viewComponent = $this->viewConfig->viewComponents[$name] ?? null; |
| 53 | + |
| 54 | + $element = new ViewComponentElement( |
| 55 | + environment: $this->appConfig->environment, |
| 56 | + compiler: $this->compiler, |
| 57 | + elementFactory: $this->elementFactory, |
| 58 | + viewComponent: $viewComponent, |
| 59 | + attributes: $attributes, |
| 60 | + ); |
| 61 | + |
| 62 | + return $element->compile(); |
| 63 | + } |
| 64 | +} |
0 commit comments