|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace Contributte\FormWizard\Latte; |
| 4 | + |
| 5 | +use Contributte\FormWizard\Facade; |
| 6 | +use Contributte\FormWizard\IWizard; |
| 7 | +use Generator; |
| 8 | +use Latte\Compiler\NodeHelpers; |
| 9 | +use Latte\Compiler\Nodes\AreaNode; |
| 10 | +use Latte\Compiler\Nodes\Php\ExpressionNode; |
| 11 | +use Latte\Compiler\Nodes\StatementNode; |
| 12 | +use Latte\Compiler\PrintContext; |
| 13 | +use Latte\Compiler\Tag; |
| 14 | +use Nette\ComponentModel\IComponent; |
| 15 | + |
| 16 | +final class WizardNode extends StatementNode |
| 17 | +{ |
| 18 | + |
| 19 | + /** @var ExpressionNode */ |
| 20 | + public $name; |
| 21 | + |
| 22 | + /** @var AreaNode */ |
| 23 | + public $content; |
| 24 | + |
| 25 | + /** |
| 26 | + * @return Generator<int, ?mixed[], array{AreaNode, ?Tag}, self> |
| 27 | + */ |
| 28 | + public static function create(Tag $tag): Generator |
| 29 | + { |
| 30 | + $tag->outputMode = $tag::OutputRemoveIndentation; |
| 31 | + $tag->expectArguments(); |
| 32 | + |
| 33 | + $node = new static; |
| 34 | + $node->name = $tag->parser->parseUnquotedStringOrExpression(); |
| 35 | + |
| 36 | + [$node->content] = yield; |
| 37 | + |
| 38 | + return $node; |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * @throws Exception |
| 43 | + */ |
| 44 | + public static function createFacade(IComponent $component): Facade |
| 45 | + { |
| 46 | + if (!$component instanceof IWizard) { |
| 47 | + throw new Exception('Wizard must be instance of ' . IWizard::class); |
| 48 | + } |
| 49 | + |
| 50 | + return new Facade($component); |
| 51 | + } |
| 52 | + |
| 53 | + public function print(PrintContext $context): string |
| 54 | + { |
| 55 | + $nameValue = static::toValue($this->name); |
| 56 | + $componentGetter = '$this->global->uiControl->getComponent("' . $nameValue . '")'; |
| 57 | + // variable : getter |
| 58 | + $wizardGetter = $nameValue[0] === '$' ? sprintf('is_object(%s) ? %s : %s', $nameValue, $nameValue, $componentGetter) : $componentGetter; |
| 59 | + |
| 60 | + return $context->format( |
| 61 | + '$wizard = %raw::createFacade(%raw);' |
| 62 | + . "\n" |
| 63 | + . ' %line %node ' // content |
| 64 | + . "\n\n", |
| 65 | + static::class, |
| 66 | + $wizardGetter, |
| 67 | + $this->position, |
| 68 | + $this->content |
| 69 | + ); |
| 70 | + } |
| 71 | + public function &getIterator(): \Generator |
| 72 | + { |
| 73 | + yield $this->name; |
| 74 | + yield $this->content; |
| 75 | + } |
| 76 | + |
| 77 | + public static function toValue($args): mixed |
| 78 | + { |
| 79 | + try { |
| 80 | + return NodeHelpers::toValue($args, constants: true); |
| 81 | + } catch (\InvalidArgumentException) { |
| 82 | + return null; |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | +} |
0 commit comments