-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #10 from JBlond/twig-trans-9
Fix: Twig removed MacroAutoImportNodeVisitor in Twig v3.15.0
- Loading branch information
Showing
2 changed files
with
69 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters