winter/modules/cms/twig/ComponentNode.php
Luke Towers 5b8d189df4 Fix issues with accessing the expected context variables inside of Twig macros.
This fixes #578 by adding the ability to pass the CMS Controller instance to the CMS Twig Extension removing the reliance on context variables as well as making the expected "global" twig variables inside of the CMS Twig environment actually global within that environment.

Replaces #598 & #593.

Credit to @RomainMazB for the initial implementation.
2022-07-10 01:09:09 -06:00

46 lines
1.4 KiB
PHP

<?php namespace Cms\Twig;
use Twig\Node\Node as TwigNode;
use Twig\Compiler as TwigCompiler;
/**
* Represents a component node
*
* @package winter\wn-cms-module
* @author Alexey Bobkov, Samuel Georges
*/
class ComponentNode extends TwigNode
{
public function __construct(TwigNode $nodes, $paramNames, $lineno, $tag = 'component')
{
parent::__construct(['nodes' => $nodes], ['names' => $paramNames], $lineno, $tag);
}
/**
* Compiles the node to PHP.
*
* @param TwigCompiler $compiler A TwigCompiler instance
*/
public function compile(TwigCompiler $compiler)
{
$compiler->addDebugInfo($this);
$compiler->write("\$context['__cms_component_params'] = [];\n");
for ($i = 1; $i < count($this->getNode('nodes')); $i++) {
$compiler->write("\$context['__cms_component_params']['".$this->getAttribute('names')[$i-1]."'] = ");
$compiler->subcompile($this->getNode('nodes')->getNode($i));
$compiler->write(";\n");
}
$compiler
->write("echo \$this->env->getExtension('Cms\Twig\Extension')->componentFunction(")
->subcompile($this->getNode('nodes')->getNode(0))
->write(", \$context['__cms_component_params']")
->write(");\n")
;
$compiler->write("unset(\$context['__cms_component_params']);\n");
}
}