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

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 ($this->getCurrentToken()->getType()) {
  127.                 case Token::TEXT_TYPE:
  128.                     $token $this->stream->next();
  129.                     $rv[] = new TextNode($token->getValue(), $token->getLine());
  130.                     break;
  131.                 case 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 Token::BLOCK_START_TYPE:
  138.                     $this->stream->next();
  139.                     $token $this->getCurrentToken();
  140.                     if (Token::NAME_TYPE !== $token->getType()) {
  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.     public function peekBlockStack()
  190.     {
  191.         return $this->blockStack[\count($this->blockStack) - 1] ?? null;
  192.     }
  193.     public function popBlockStack(): void
  194.     {
  195.         array_pop($this->blockStack);
  196.     }
  197.     public function pushBlockStack($name): void
  198.     {
  199.         $this->blockStack[] = $name;
  200.     }
  201.     public function hasBlock(string $name): bool
  202.     {
  203.         trigger_deprecation('twig/twig''3.12''Method "%s()" is deprecated.'__METHOD__);
  204.         return isset($this->blocks[$name]);
  205.     }
  206.     public function getBlock(string $name): Node
  207.     {
  208.         trigger_deprecation('twig/twig''3.12''Method "%s()" is deprecated.'__METHOD__);
  209.         return $this->blocks[$name];
  210.     }
  211.     public function setBlock(string $nameBlockNode $value): void
  212.     {
  213.         if (isset($this->blocks[$name])) {
  214.             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());
  215.         }
  216.         $this->blocks[$name] = new BodyNode([$value], [], $value->getTemplateLine());
  217.     }
  218.     public function hasMacro(string $name): bool
  219.     {
  220.         trigger_deprecation('twig/twig''3.12''Method "%s()" is deprecated.'__METHOD__);
  221.         return isset($this->macros[$name]);
  222.     }
  223.     public function setMacro(string $nameMacroNode $node): void
  224.     {
  225.         $this->macros[$name] = $node;
  226.     }
  227.     public function addTrait($trait): void
  228.     {
  229.         $this->traits[] = $trait;
  230.     }
  231.     public function hasTraits(): bool
  232.     {
  233.         trigger_deprecation('twig/twig''3.12''Method "%s()" is deprecated.'__METHOD__);
  234.         return \count($this->traits) > 0;
  235.     }
  236.     public function embedTemplate(ModuleNode $template)
  237.     {
  238.         $template->setIndex(mt_rand());
  239.         $this->embeddedTemplates[] = $template;
  240.     }
  241.     public function addImportedSymbol(string $typestring $alias, ?string $name nullAbstractExpression|AssignTemplateVariable|null $internalRef null): void
  242.     {
  243.         if ($internalRef && !$internalRef instanceof AssignTemplateVariable) {
  244.             trigger_deprecation('twig/twig''3.15''Not passing a "%s" instance as an internal reference is deprecated ("%s" given).'__METHOD__AssignTemplateVariable::class, $internalRef::class);
  245.             $internalRef = new AssignTemplateVariable(new TemplateVariable($internalRef->getAttribute('name'), $internalRef->getTemplateLine()), $internalRef->getAttribute('global'));
  246.         }
  247.         $this->importedSymbols[0][$type][$alias] = ['name' => $name'node' => $internalRef];
  248.     }
  249.     public function getImportedSymbol(string $typestring $alias)
  250.     {
  251.         // if the symbol does not exist in the current scope (0), try in the main/global scope (last index)
  252.         return $this->importedSymbols[0][$type][$alias] ?? ($this->importedSymbols[\count($this->importedSymbols) - 1][$type][$alias] ?? null);
  253.     }
  254.     public function isMainScope(): bool
  255.     {
  256.         return === \count($this->importedSymbols);
  257.     }
  258.     public function pushLocalScope(): void
  259.     {
  260.         array_unshift($this->importedSymbols, []);
  261.     }
  262.     public function popLocalScope(): void
  263.     {
  264.         array_shift($this->importedSymbols);
  265.     }
  266.     public function getExpressionParser(): ExpressionParser
  267.     {
  268.         return $this->expressionParser;
  269.     }
  270.     public function getParent(): ?Node
  271.     {
  272.         trigger_deprecation('twig/twig''3.12''Method "%s()" is deprecated.'__METHOD__);
  273.         return $this->parent;
  274.     }
  275.     public function hasInheritance()
  276.     {
  277.         return $this->parent || \count($this->traits);
  278.     }
  279.     public function setParent(?Node $parent): void
  280.     {
  281.         if (null === $parent) {
  282.             trigger_deprecation('twig/twig''3.12''Passing "null" to "%s()" is deprecated.'__METHOD__);
  283.         }
  284.         if (null !== $this->parent) {
  285.             throw new SyntaxError('Multiple extends tags are forbidden.'$parent->getTemplateLine(), $parent->getSourceContext());
  286.         }
  287.         $this->parent $parent;
  288.     }
  289.     public function getStream(): TokenStream
  290.     {
  291.         return $this->stream;
  292.     }
  293.     public function getCurrentToken(): Token
  294.     {
  295.         return $this->stream->getCurrent();
  296.     }
  297.     private function filterBodyNodes(Node $nodebool $nested false): ?Node
  298.     {
  299.         // check that the body does not contain non-empty output nodes
  300.         if (
  301.             ($node instanceof TextNode && !ctype_space($node->getAttribute('data')))
  302.             || (!$node instanceof TextNode && !$node instanceof BlockReferenceNode && $node instanceof NodeOutputInterface)
  303.         ) {
  304.             if (str_contains((string) $node\chr(0xEF).\chr(0xBB).\chr(0xBF))) {
  305.                 $t substr($node->getAttribute('data'), 3);
  306.                 if ('' === $t || ctype_space($t)) {
  307.                     // bypass empty nodes starting with a BOM
  308.                     return null;
  309.                 }
  310.             }
  311.             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());
  312.         }
  313.         // bypass nodes that "capture" the output
  314.         if ($node instanceof NodeCaptureInterface) {
  315.             // a "block" tag in such a node will serve as a block definition AND be displayed in place as well
  316.             return $node;
  317.         }
  318.         // "block" tags that are not captured (see above) are only used for defining
  319.         // the content of the block. In such a case, nesting it does not work as
  320.         // expected as the definition is not part of the default template code flow.
  321.         if ($nested && $node instanceof BlockReferenceNode) {
  322.             throw new SyntaxError('A block definition cannot be nested under non-capturing nodes.'$node->getTemplateLine(), $this->stream->getSourceContext());
  323.         }
  324.         if ($node instanceof NodeOutputInterface) {
  325.             return null;
  326.         }
  327.         // here, $nested means "being at the root level of a child template"
  328.         // we need to discard the wrapping "Node" for the "body" node
  329.         // Node::class !== \get_class($node) should be removed in Twig 4.0
  330.         $nested $nested || (Node::class !== \get_class($node) && !$node instanceof Nodes);
  331.         foreach ($node as $k => $n) {
  332.             if (null !== $n && null === $this->filterBodyNodes($n$nested)) {
  333.                 $node->removeNode($k);
  334.             }
  335.         }
  336.         return $node;
  337.     }
  338. }