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

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. final class MacroTokenParser extends AbstractTokenParser
  24. {
  25. public function parse(Token $token)
  26. {
  27. $lineno = $token->getLine();
  28. $stream = $this->parser->getStream();
  29. $name = $stream->expect(/* Token::NAME_TYPE */ 5)->getValue();
  30. $arguments = $this->parser->getExpressionParser()->parseArguments(true, true);
  31. $stream->expect(/* Token::BLOCK_END_TYPE */ 3);
  32. $this->parser->pushLocalScope();
  33. $body = $this->parser->subparse([$this, 'decideBlockEnd'], true);
  34. if ($token = $stream->nextIf(/* Token::NAME_TYPE */ 5)) {
  35. $value = $token->getValue();
  36. if ($value != $name) {
  37. throw new SyntaxError(sprintf('Expected endmacro for macro "%s" (but "%s" given).', $name, $value), $stream->getCurrent()->getLine(), $stream->getSourceContext());
  38. }
  39. }
  40. $this->parser->popLocalScope();
  41. $stream->expect(/* Token::BLOCK_END_TYPE */ 3);
  42. $this->parser->setMacro($name, new MacroNode($name, new BodyNode([$body]), $arguments, $lineno, $this->getTag()));
  43. return new Node();
  44. }
  45. public function decideBlockEnd(Token $token)
  46. {
  47. return $token->test('endmacro');
  48. }
  49. public function getTag()
  50. {
  51. return 'macro';
  52. }
  53. }
  54. class_alias('Twig\TokenParser\MacroTokenParser', 'Twig_TokenParser_Macro');