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

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