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

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