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

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