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

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\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. /**
  26.  * @author Fabien Potencier <fabien@symfony.com>
  27.  */
  28. class Parser
  29. {
  30.     private $stack = [];
  31.     private $stream;
  32.     private $parent;
  33.     private $visitors;
  34.     private $expressionParser;
  35.     private $blocks;
  36.     private $blockStack;
  37.     private $macros;
  38.     private $env;
  39.     private $importedSymbols;
  40.     private $traits;
  41.     private $embeddedTemplates = [];
  42.     private $varNameSalt 0;
  43.     public function __construct(Environment $env)
  44.     {
  45.         $this->env $env;
  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->stream->getCurrent()->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 */ 0:
  104.                     $token $this->stream->next();
  105.                     $rv[] = new TextNode($token->getValue(), $token->getLine());
  106.                     break;
  107.                 case /* Token::VAR_START_TYPE */ 2:
  108.                     $token $this->stream->next();
  109.                     $expr $this->expressionParser->parseExpression();
  110.                     $this->stream->expect(/* Token::VAR_END_TYPE */ 4);
  111.                     $rv[] = new PrintNode($expr$token->getLine());
  112.                     break;
  113.                 case /* Token::BLOCK_START_TYPE */ 1:
  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.                             if (\is_array($test) && isset($test[0]) && $test[0] instanceof TokenParserInterface) {
  132.                                 $e->appendMessage(sprintf(' (expecting closing tag for the "%s" tag defined near line %s).'$test[0]->getTag(), $lineno));
  133.                             }
  134.                         } else {
  135.                             $e = new SyntaxError(sprintf('Unknown "%s" tag.'$token->getValue()), $token->getLine(), $this->stream->getSourceContext());
  136.                             $e->addSuggestions($token->getValue(), array_keys($this->env->getTokenParsers()));
  137.                         }
  138.                         throw $e;
  139.                     }
  140.                     $this->stream->next();
  141.                     $subparser->setParser($this);
  142.                     $node $subparser->parse($token);
  143.                     if (null !== $node) {
  144.                         $rv[] = $node;
  145.                     }
  146.                     break;
  147.                 default:
  148.                     throw new SyntaxError('Lexer or parser ended up in unsupported state.'$this->getCurrentToken()->getLine(), $this->stream->getSourceContext());
  149.             }
  150.         }
  151.         if (=== \count($rv)) {
  152.             return $rv[0];
  153.         }
  154.         return new Node($rv, [], $lineno);
  155.     }
  156.     public function getBlockStack(): array
  157.     {
  158.         return $this->blockStack;
  159.     }
  160.     public function peekBlockStack()
  161.     {
  162.         return $this->blockStack[\count($this->blockStack) - 1] ?? null;
  163.     }
  164.     public function popBlockStack(): void
  165.     {
  166.         array_pop($this->blockStack);
  167.     }
  168.     public function pushBlockStack($name): void
  169.     {
  170.         $this->blockStack[] = $name;
  171.     }
  172.     public function hasBlock(string $name): bool
  173.     {
  174.         return isset($this->blocks[$name]);
  175.     }
  176.     public function getBlock(string $name): Node
  177.     {
  178.         return $this->blocks[$name];
  179.     }
  180.     public function setBlock(string $nameBlockNode $value): void
  181.     {
  182.         $this->blocks[$name] = new BodyNode([$value], [], $value->getTemplateLine());
  183.     }
  184.     public function hasMacro(string $name): bool
  185.     {
  186.         return isset($this->macros[$name]);
  187.     }
  188.     public function setMacro(string $nameMacroNode $node): void
  189.     {
  190.         $this->macros[$name] = $node;
  191.     }
  192.     public function addTrait($trait): void
  193.     {
  194.         $this->traits[] = $trait;
  195.     }
  196.     public function hasTraits(): bool
  197.     {
  198.         return \count($this->traits) > 0;
  199.     }
  200.     public function embedTemplate(ModuleNode $template)
  201.     {
  202.         $template->setIndex(mt_rand());
  203.         $this->embeddedTemplates[] = $template;
  204.     }
  205.     public function addImportedSymbol(string $typestring $alias, ?string $name null, ?AbstractExpression $node null): void
  206.     {
  207.         $this->importedSymbols[0][$type][$alias] = ['name' => $name'node' => $node];
  208.     }
  209.     public function getImportedSymbol(string $typestring $alias)
  210.     {
  211.         // if the symbol does not exist in the current scope (0), try in the main/global scope (last index)
  212.         return $this->importedSymbols[0][$type][$alias] ?? ($this->importedSymbols[\count($this->importedSymbols) - 1][$type][$alias] ?? null);
  213.     }
  214.     public function isMainScope(): bool
  215.     {
  216.         return === \count($this->importedSymbols);
  217.     }
  218.     public function pushLocalScope(): void
  219.     {
  220.         array_unshift($this->importedSymbols, []);
  221.     }
  222.     public function popLocalScope(): void
  223.     {
  224.         array_shift($this->importedSymbols);
  225.     }
  226.     public function getExpressionParser(): ExpressionParser
  227.     {
  228.         return $this->expressionParser;
  229.     }
  230.     public function getParent(): ?Node
  231.     {
  232.         return $this->parent;
  233.     }
  234.     public function setParent(?Node $parent): void
  235.     {
  236.         $this->parent $parent;
  237.     }
  238.     public function getStream(): TokenStream
  239.     {
  240.         return $this->stream;
  241.     }
  242.     public function getCurrentToken(): Token
  243.     {
  244.         return $this->stream->getCurrent();
  245.     }
  246.     private function filterBodyNodes(Node $nodebool $nested false): ?Node
  247.     {
  248.         // check that the body does not contain non-empty output nodes
  249.         if (
  250.             ($node instanceof TextNode && !ctype_space($node->getAttribute('data')))
  251.             || (!$node instanceof TextNode && !$node instanceof BlockReferenceNode && $node instanceof NodeOutputInterface)
  252.         ) {
  253.             if (str_contains((string) $node\chr(0xEF).\chr(0xBB).\chr(0xBF))) {
  254.                 $t substr($node->getAttribute('data'), 3);
  255.                 if ('' === $t || ctype_space($t)) {
  256.                     // bypass empty nodes starting with a BOM
  257.                     return null;
  258.                 }
  259.             }
  260.             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());
  261.         }
  262.         // bypass nodes that "capture" the output
  263.         if ($node instanceof NodeCaptureInterface) {
  264.             // a "block" tag in such a node will serve as a block definition AND be displayed in place as well
  265.             return $node;
  266.         }
  267.         // "block" tags that are not captured (see above) are only used for defining
  268.         // the content of the block. In such a case, nesting it does not work as
  269.         // expected as the definition is not part of the default template code flow.
  270.         if ($nested && $node instanceof BlockReferenceNode) {
  271.             throw new SyntaxError('A block definition cannot be nested under non-capturing nodes.'$node->getTemplateLine(), $this->stream->getSourceContext());
  272.         }
  273.         if ($node instanceof NodeOutputInterface) {
  274.             return null;
  275.         }
  276.         // here, $nested means "being at the root level of a child template"
  277.         // we need to discard the wrapping "Node" for the "body" node
  278.         $nested $nested || Node::class !== \get_class($node);
  279.         foreach ($node as $k => $n) {
  280.             if (null !== $n && null === $this->filterBodyNodes($n$nested)) {
  281.                 $node->removeNode($k);
  282.             }
  283.         }
  284.         return $node;
  285.     }
  286. }