vendor/twig/twig/src/Parser.php line 257

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of Twig.
  4.  *
  5.  * (c) Fabien Potencier
  6.  * (c) Armin Ronacher
  7.  *
  8.  * For the full copyright and license information, please view the LICENSE
  9.  * file that was distributed with this source code.
  10.  */
  11. namespace Twig;
  12. use Twig\Error\SyntaxError;
  13. use Twig\Node\BlockNode;
  14. use Twig\Node\BlockReferenceNode;
  15. use Twig\Node\BodyNode;
  16. use Twig\Node\EmptyNode;
  17. use Twig\Node\Expression\AbstractExpression;
  18. use Twig\Node\Expression\Variable\AssignTemplateVariable;
  19. use Twig\Node\Expression\Variable\TemplateVariable;
  20. use Twig\Node\MacroNode;
  21. use Twig\Node\ModuleNode;
  22. use Twig\Node\Node;
  23. use Twig\Node\NodeCaptureInterface;
  24. use Twig\Node\NodeOutputInterface;
  25. use Twig\Node\Nodes;
  26. use Twig\Node\PrintNode;
  27. use Twig\Node\TextNode;
  28. use Twig\TokenParser\TokenParserInterface;
  29. use Twig\Util\ReflectionCallable;
  30. /**
  31.  * @author Fabien Potencier <fabien@symfony.com>
  32.  */
  33. class Parser
  34. {
  35.     private $stack = [];
  36.     private $stream;
  37.     private $parent;
  38.     private $visitors;
  39.     private $expressionParser;
  40.     private $blocks;
  41.     private $blockStack;
  42.     private $macros;
  43.     private $importedSymbols;
  44.     private $traits;
  45.     private $embeddedTemplates = [];
  46.     private $varNameSalt 0;
  47.     private $ignoreUnknownTwigCallables false;
  48.     public function __construct(
  49.         private Environment $env,
  50.     ) {
  51.     }
  52.     public function getEnvironment(): Environment
  53.     {
  54.         return $this->env;
  55.     }
  56.     public function getVarName(): string
  57.     {
  58.         trigger_deprecation('twig/twig''3.15''The "%s()" method is deprecated.'__METHOD__);
  59.         return \sprintf('__internal_parse_%d'$this->varNameSalt++);
  60.     }
  61.     public function parse(TokenStream $stream$test nullbool $dropNeedle false): ModuleNode
  62.     {
  63.         $vars get_object_vars($this);
  64.         unset($vars['stack'], $vars['env'], $vars['handlers'], $vars['visitors'], $vars['expressionParser'], $vars['reservedMacroNames'], $vars['varNameSalt']);
  65.         $this->stack[] = $vars;
  66.         // node visitors
  67.         if (null === $this->visitors) {
  68.             $this->visitors $this->env->getNodeVisitors();
  69.         }
  70.         if (null === $this->expressionParser) {
  71.             $this->expressionParser = new ExpressionParser($this$this->env);
  72.         }
  73.         $this->stream $stream;
  74.         $this->parent null;
  75.         $this->blocks = [];
  76.         $this->macros = [];
  77.         $this->traits = [];
  78.         $this->blockStack = [];
  79.         $this->importedSymbols = [[]];
  80.         $this->embeddedTemplates = [];
  81.         try {
  82.             $body $this->subparse($test$dropNeedle);
  83.             if (null !== $this->parent && null === $body $this->filterBodyNodes($body)) {
  84.                 $body = new EmptyNode();
  85.             }
  86.         } catch (SyntaxError $e) {
  87.             if (!$e->getSourceContext()) {
  88.                 $e->setSourceContext($this->stream->getSourceContext());
  89.             }
  90.             if (!$e->getTemplateLine()) {
  91.                 $e->setTemplateLine($this->getCurrentToken()->getLine());
  92.             }
  93.             throw $e;
  94.         }
  95.         $node = new ModuleNode(new BodyNode([$body]), $this->parent, new Nodes($this->blocks), new Nodes($this->macros), new Nodes($this->traits), $this->embeddedTemplates$stream->getSourceContext());
  96.         $traverser = new NodeTraverser($this->env$this->visitors);
  97.         /**
  98.          * @var ModuleNode $node
  99.          */
  100.         $node $traverser->traverse($node);
  101.         // restore previous stack so previous parse() call can resume working
  102.         foreach (array_pop($this->stack) as $key => $val) {
  103.             $this->$key $val;
  104.         }
  105.         return $node;
  106.     }
  107.     public function shouldIgnoreUnknownTwigCallables(): bool
  108.     {
  109.         return $this->ignoreUnknownTwigCallables;
  110.     }
  111.     public function subparseIgnoreUnknownTwigCallables($testbool $dropNeedle false): void
  112.     {
  113.         $previous $this->ignoreUnknownTwigCallables;
  114.         $this->ignoreUnknownTwigCallables true;
  115.         try {
  116.             $this->subparse($test$dropNeedle);
  117.         } finally {
  118.             $this->ignoreUnknownTwigCallables $previous;
  119.         }
  120.     }
  121.     public function subparse($testbool $dropNeedle false): Node
  122.     {
  123.         $lineno $this->getCurrentToken()->getLine();
  124.         $rv = [];
  125.         while (!$this->stream->isEOF()) {
  126.             switch (true) {
  127.                 case $this->stream->getCurrent()->test(Token::TEXT_TYPE):
  128.                     $token $this->stream->next();
  129.                     $rv[] = new TextNode($token->getValue(), $token->getLine());
  130.                     break;
  131.                 case $this->stream->getCurrent()->test(Token::VAR_START_TYPE):
  132.                     $token $this->stream->next();
  133.                     $expr $this->expressionParser->parseExpression();
  134.                     $this->stream->expect(Token::VAR_END_TYPE);
  135.                     $rv[] = new PrintNode($expr$token->getLine());
  136.                     break;
  137.                 case $this->stream->getCurrent()->test(Token::BLOCK_START_TYPE):
  138.                     $this->stream->next();
  139.                     $token $this->getCurrentToken();
  140.                     if (!$token->test(Token::NAME_TYPE)) {
  141.                         throw new SyntaxError('A block must start with a tag name.'$token->getLine(), $this->stream->getSourceContext());
  142.                     }
  143.                     if (null !== $test && $test($token)) {
  144.                         if ($dropNeedle) {
  145.                             $this->stream->next();
  146.                         }
  147.                         if (=== \count($rv)) {
  148.                             return $rv[0];
  149.                         }
  150.                         return new Nodes($rv$lineno);
  151.                     }
  152.                     if (!$subparser $this->env->getTokenParser($token->getValue())) {
  153.                         if (null !== $test) {
  154.                             $e = new SyntaxError(\sprintf('Unexpected "%s" tag'$token->getValue()), $token->getLine(), $this->stream->getSourceContext());
  155.                             $callable = (new ReflectionCallable(new TwigTest('decision'$test)))->getCallable();
  156.                             if (\is_array($callable) && $callable[0] instanceof TokenParserInterface) {
  157.                                 $e->appendMessage(\sprintf(' (expecting closing tag for the "%s" tag defined near line %s).'$callable[0]->getTag(), $lineno));
  158.                             }
  159.                         } else {
  160.                             $e = new SyntaxError(\sprintf('Unknown "%s" tag.'$token->getValue()), $token->getLine(), $this->stream->getSourceContext());
  161.                             $e->addSuggestions($token->getValue(), array_keys($this->env->getTokenParsers()));
  162.                         }
  163.                         throw $e;
  164.                     }
  165.                     $this->stream->next();
  166.                     $subparser->setParser($this);
  167.                     $node $subparser->parse($token);
  168.                     if (!$node) {
  169.                         trigger_deprecation('twig/twig''3.12''Returning "null" from "%s" is deprecated and forbidden by "TokenParserInterface".'$subparser::class);
  170.                     } else {
  171.                         $node->setNodeTag($subparser->getTag());
  172.                         $rv[] = $node;
  173.                     }
  174.                     break;
  175.                 default:
  176.                     throw new SyntaxError('The lexer or the parser ended up in an unsupported state.'$this->getCurrentToken()->getLine(), $this->stream->getSourceContext());
  177.             }
  178.         }
  179.         if (=== \count($rv)) {
  180.             return $rv[0];
  181.         }
  182.         return new Nodes($rv$lineno);
  183.     }
  184.     public function getBlockStack(): array
  185.     {
  186.         trigger_deprecation('twig/twig''3.12''Method "%s()" is deprecated.'__METHOD__);
  187.         return $this->blockStack;
  188.     }
  189.     /**
  190.      * @return string|null
  191.      */
  192.     public function peekBlockStack()
  193.     {
  194.         return $this->blockStack[\count($this->blockStack) - 1] ?? null;
  195.     }
  196.     public function popBlockStack(): void
  197.     {
  198.         array_pop($this->blockStack);
  199.     }
  200.     public function pushBlockStack($name): void
  201.     {
  202.         $this->blockStack[] = $name;
  203.     }
  204.     public function hasBlock(string $name): bool
  205.     {
  206.         trigger_deprecation('twig/twig''3.12''Method "%s()" is deprecated.'__METHOD__);
  207.         return isset($this->blocks[$name]);
  208.     }
  209.     public function getBlock(string $name): Node
  210.     {
  211.         trigger_deprecation('twig/twig''3.12''Method "%s()" is deprecated.'__METHOD__);
  212.         return $this->blocks[$name];
  213.     }
  214.     public function setBlock(string $nameBlockNode $value): void
  215.     {
  216.         if (isset($this->blocks[$name])) {
  217.             throw new SyntaxError(\sprintf("The block '%s' has already been defined line %d."$name$this->blocks[$name]->getTemplateLine()), $this->getCurrentToken()->getLine(), $this->blocks[$name]->getSourceContext());
  218.         }
  219.         $this->blocks[$name] = new BodyNode([$value], [], $value->getTemplateLine());
  220.     }
  221.     public function hasMacro(string $name): bool
  222.     {
  223.         trigger_deprecation('twig/twig''3.12''Method "%s()" is deprecated.'__METHOD__);
  224.         return isset($this->macros[$name]);
  225.     }
  226.     public function setMacro(string $nameMacroNode $node): void
  227.     {
  228.         $this->macros[$name] = $node;
  229.     }
  230.     public function addTrait($trait): void
  231.     {
  232.         $this->traits[] = $trait;
  233.     }
  234.     public function hasTraits(): bool
  235.     {
  236.         trigger_deprecation('twig/twig''3.12''Method "%s()" is deprecated.'__METHOD__);
  237.         return \count($this->traits) > 0;
  238.     }
  239.     /**
  240.      * @return void
  241.      */
  242.     public function embedTemplate(ModuleNode $template)
  243.     {
  244.         $template->setIndex(mt_rand());
  245.         $this->embeddedTemplates[] = $template;
  246.     }
  247.     public function addImportedSymbol(string $typestring $alias, ?string $name nullAbstractExpression|AssignTemplateVariable|null $internalRef null): void
  248.     {
  249.         if ($internalRef && !$internalRef instanceof AssignTemplateVariable) {
  250.             trigger_deprecation('twig/twig''3.15''Not passing a "%s" instance as an internal reference is deprecated ("%s" given).'__METHOD__AssignTemplateVariable::class, $internalRef::class);
  251.             $internalRef = new AssignTemplateVariable(new TemplateVariable($internalRef->getAttribute('name'), $internalRef->getTemplateLine()), $internalRef->getAttribute('global'));
  252.         }
  253.         $this->importedSymbols[0][$type][$alias] = ['name' => $name'node' => $internalRef];
  254.     }
  255.     /**
  256.      * @return array{name: string, node: AssignTemplateVariable|null}|null
  257.      */
  258.     public function getImportedSymbol(string $typestring $alias)
  259.     {
  260.         // if the symbol does not exist in the current scope (0), try in the main/global scope (last index)
  261.         return $this->importedSymbols[0][$type][$alias] ?? ($this->importedSymbols[\count($this->importedSymbols) - 1][$type][$alias] ?? null);
  262.     }
  263.     public function isMainScope(): bool
  264.     {
  265.         return === \count($this->importedSymbols);
  266.     }
  267.     public function pushLocalScope(): void
  268.     {
  269.         array_unshift($this->importedSymbols, []);
  270.     }
  271.     public function popLocalScope(): void
  272.     {
  273.         array_shift($this->importedSymbols);
  274.     }
  275.     public function getExpressionParser(): ExpressionParser
  276.     {
  277.         return $this->expressionParser;
  278.     }
  279.     public function getParent(): ?Node
  280.     {
  281.         trigger_deprecation('twig/twig''3.12''Method "%s()" is deprecated.'__METHOD__);
  282.         return $this->parent;
  283.     }
  284.     /**
  285.      * @return bool
  286.      */
  287.     public function hasInheritance()
  288.     {
  289.         return $this->parent || \count($this->traits);
  290.     }
  291.     public function setParent(?Node $parent): void
  292.     {
  293.         if (null === $parent) {
  294.             trigger_deprecation('twig/twig''3.12''Passing "null" to "%s()" is deprecated.'__METHOD__);
  295.         }
  296.         if (null !== $this->parent) {
  297.             throw new SyntaxError('Multiple extends tags are forbidden.'$parent->getTemplateLine(), $parent->getSourceContext());
  298.         }
  299.         $this->parent $parent;
  300.     }
  301.     public function getStream(): TokenStream
  302.     {
  303.         return $this->stream;
  304.     }
  305.     public function getCurrentToken(): Token
  306.     {
  307.         return $this->stream->getCurrent();
  308.     }
  309.     private function filterBodyNodes(Node $nodebool $nested false): ?Node
  310.     {
  311.         // check that the body does not contain non-empty output nodes
  312.         if (
  313.             ($node instanceof TextNode && !ctype_space($node->getAttribute('data')))
  314.             || (!$node instanceof TextNode && !$node instanceof BlockReferenceNode && $node instanceof NodeOutputInterface)
  315.         ) {
  316.             if (str_contains((string) $node\chr(0xEF).\chr(0xBB).\chr(0xBF))) {
  317.                 $t substr($node->getAttribute('data'), 3);
  318.                 if ('' === $t || ctype_space($t)) {
  319.                     // bypass empty nodes starting with a BOM
  320.                     return null;
  321.                 }
  322.             }
  323.             throw new SyntaxError('A template that extends another one cannot include content outside Twig blocks. Did you forget to put the content inside a {% block %} tag?'$node->getTemplateLine(), $this->stream->getSourceContext());
  324.         }
  325.         // bypass nodes that "capture" the output
  326.         if ($node instanceof NodeCaptureInterface) {
  327.             // a "block" tag in such a node will serve as a block definition AND be displayed in place as well
  328.             return $node;
  329.         }
  330.         // "block" tags that are not captured (see above) are only used for defining
  331.         // the content of the block. In such a case, nesting it does not work as
  332.         // expected as the definition is not part of the default template code flow.
  333.         if ($nested && $node instanceof BlockReferenceNode) {
  334.             throw new SyntaxError('A block definition cannot be nested under non-capturing nodes.'$node->getTemplateLine(), $this->stream->getSourceContext());
  335.         }
  336.         if ($node instanceof NodeOutputInterface) {
  337.             return null;
  338.         }
  339.         // here, $nested means "being at the root level of a child template"
  340.         // we need to discard the wrapping "Node" for the "body" node
  341.         // Node::class !== \get_class($node) should be removed in Twig 4.0
  342.         $nested $nested || (Node::class !== \get_class($node) && !$node instanceof Nodes);
  343.         foreach ($node as $k => $n) {
  344.             if (null !== $n && null === $this->filterBodyNodes($n$nested)) {
  345.                 $node->removeNode($k);
  346.             }
  347.         }
  348.         return $node;
  349.     }
  350. }