vendor/twig/twig/src/TokenParser/MacroTokenParser.php line 52

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of Twig.
  4.  *
  5.  * (c) Fabien Potencier
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Twig\TokenParser;
  11. use Twig\Error\SyntaxError;
  12. use Twig\Node\BodyNode;
  13. use Twig\Node\MacroNode;
  14. use Twig\Node\Node;
  15. use Twig\Token;
  16. /**
  17.  * Defines a macro.
  18.  *
  19.  *   {% macro input(name, value, type, size) %}
  20.  *      <input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" size="{{ size|default(20) }}" />
  21.  *   {% endmacro %}
  22.  *
  23.  * @internal
  24.  */
  25. final class MacroTokenParser extends AbstractTokenParser
  26. {
  27.     public function parse(Token $token): Node
  28.     {
  29.         $lineno $token->getLine();
  30.         $stream $this->parser->getStream();
  31.         $name $stream->expect(/* Token::NAME_TYPE */ 5)->getValue();
  32.         $arguments $this->parser->getExpressionParser()->parseArguments(truetrue);
  33.         $stream->expect(/* Token::BLOCK_END_TYPE */ 3);
  34.         $this->parser->pushLocalScope();
  35.         $body $this->parser->subparse([$this'decideBlockEnd'], true);
  36.         if ($token $stream->nextIf(/* Token::NAME_TYPE */ 5)) {
  37.             $value $token->getValue();
  38.             if ($value != $name) {
  39.                 throw new SyntaxError(sprintf('Expected endmacro for macro "%s" (but "%s" given).'$name$value), $stream->getCurrent()->getLine(), $stream->getSourceContext());
  40.             }
  41.         }
  42.         $this->parser->popLocalScope();
  43.         $stream->expect(/* Token::BLOCK_END_TYPE */ 3);
  44.         $this->parser->setMacro($name, new MacroNode($name, new BodyNode([$body]), $arguments$lineno$this->getTag()));
  45.         return new Node();
  46.     }
  47.     public function decideBlockEnd(Token $token): bool
  48.     {
  49.         return $token->test('endmacro');
  50.     }
  51.     public function getTag(): string
  52.     {
  53.         return 'macro';
  54.     }
  55. }