Skip to content

Commit

Permalink
Merge pull request #10 from JBlond/twig-trans-9
Browse files Browse the repository at this point in the history
Fix: Twig removed MacroAutoImportNodeVisitor in Twig v3.15.0
  • Loading branch information
JBlond authored Nov 18, 2024
2 parents 981c40d + ccce40e commit 8d84f95
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 1 deletion.
69 changes: 69 additions & 0 deletions src/jblond/TwigTrans/MacroAutoImportNodeVisitor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?php

namespace jblond\TwigTrans;

use Twig\Environment;
use Twig\Node\Expression\AssignNameExpression;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\Expression\GetAttrExpression;
use Twig\Node\Expression\MethodCallExpression;
use Twig\Node\Expression\NameExpression;
use Twig\Node\ImportNode;
use Twig\Node\ModuleNode;
use Twig\Node\Node;
use Twig\NodeVisitor\NodeVisitorInterface;

class MacroAutoImportNodeVisitor implements NodeVisitorInterface
{
private $inAModule = false;
private $hasMacroCalls = false;

public function enterNode(Node $node, Environment $env): Node
{
if ($node instanceof ModuleNode) {
$this->inAModule = true;
$this->hasMacroCalls = false;
}

return $node;
}

public function leaveNode(Node $node, Environment $env): Node
{
if ($node instanceof ModuleNode) {
$this->inAModule = false;
if ($this->hasMacroCalls) {
$node->getNode('constructor_end')->setNode(
'_auto_macro_import',
new ImportNode(new NameExpression('_self', 0), new AssignNameExpression('_self', 0), 0, true)
);
}
} elseif ($this->inAModule) {
if (
$node instanceof GetAttrExpression
&& $node->getNode('node') instanceof NameExpression
&& '_self' === $node->getNode('node')->getAttribute('name')
&& $node->getNode('attribute') instanceof ConstantExpression
) {
$this->hasMacroCalls = true;

$name = $node->getNode('attribute')->getAttribute('value');
$node = new MethodCallExpression(
$node->getNode('node'),
'macro_' . $name,
$node->getNode('arguments'),
$node->getTemplateLine()
);
$node->setAttribute('safe', true);
}
}

return $node;
}

public function getPriority(): int
{
// we must run before auto-escaping
return -10;
}
}
1 change: 0 additions & 1 deletion src/jblond/TwigTrans/Translation.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

use Twig\Compiler;
use Twig\Extension\ExtensionInterface;
use Twig\NodeVisitor\MacroAutoImportNodeVisitor;
use Twig\TwigFilter;
use Twig\TwigFunction;
use Twig\TwigTest;
Expand Down

0 comments on commit 8d84f95

Please sign in to comment.