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