Skip to content

Commit

Permalink
yield ready update #22
Browse files Browse the repository at this point in the history
  • Loading branch information
giorgiopogliani committed May 6, 2024
1 parent 9755a62 commit 7e0cd96
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
9 changes: 6 additions & 3 deletions src/Node/ComponentNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@
use Performing\TwigComponents\Configuration;
use Performing\TwigComponents\View\ComponentAttributeBag;
use Performing\TwigComponents\View\ComponentSlot;
use Twig\Attribute\YieldReady;
use Twig\Compiler;
use Twig\Node\Expression\AbstractExpression;
use Twig\Node\Expression\ConstantExpression;

use Twig\Node\IncludeNode;
use Twig\Node\Node;

#[YieldReady]
final class ComponentNode extends IncludeNode
{
private Configuration $configuration;
Expand Down Expand Up @@ -40,16 +42,17 @@ public function compile(Compiler $compiler): void
->write('$slotsStack = $slotsStack ?? [];' . PHP_EOL)
->write('$slotsStack[] = $slots ?? [];' . PHP_EOL)
->write('$slots = [];' . PHP_EOL)
->write("ob_start();" . PHP_EOL)
->write('$slot = implode("", iterator_to_array((function () use (&$slots, &$context) {' . PHP_EOL)
->subcompile($this->getNode('slot'))
->write('$slot = ob_get_clean();' . PHP_EOL)
->write(sprintf('$%s->display(', $template));
->write("})() ?? new \EmptyIterator()));" . PHP_EOL)
->write(sprintf('yield from $%s->unwrap()->yield(', $template));

$this->addTemplateArguments($compiler);

$compiler
->raw(");\n")
->write('$slots = array_pop($slotsStack);' . PHP_EOL)
->write("yield '';")
->write("}\n");
}

Expand Down
7 changes: 5 additions & 2 deletions src/Node/SlotNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@
namespace Performing\TwigComponents\Node;

use Performing\TwigComponents\View\ComponentSlot;
use Twig\Attribute\YieldReady;
use Twig\Compiler;
use Twig\Node\Expression\AbstractExpression;
use Twig\Node\Node;

use Twig\Node\NodeOutputInterface;

#[YieldReady]
final class SlotNode extends Node implements NodeOutputInterface
{
public function __construct($name, $body, ?AbstractExpression $variables, int $lineno = 0)
Expand All @@ -25,9 +27,10 @@ public function compile(Compiler $compiler): void
$name = $this->getAttribute('name');

$compiler
->write('ob_start();')
->write('$body = (function () use (&$slots, &$context) {')
->subcompile($this->getNode('body'))
->write('$body = ob_get_clean();' . PHP_EOL)
->write('})() ?? new \EmptyIterator();' . PHP_EOL)
->write('$body = implode("", iterator_to_array($body));' . PHP_EOL)
->write("\$slots['$name'] = new " . ComponentSlot::class . "(\$body, ");

if ($this->hasNode('variables')) {
Expand Down

0 comments on commit 7e0cd96

Please sign in to comment.