1 | <?php |
---|
2 | |
---|
3 | /* |
---|
4 | * This file is part of Twig. |
---|
5 | * |
---|
6 | * (c) 2009 Fabien Potencier |
---|
7 | * (c) 2009 Armin Ronacher |
---|
8 | * |
---|
9 | * For the full copyright and license information, please view the LICENSE |
---|
10 | * file that was distributed with this source code. |
---|
11 | */ |
---|
12 | class Twig_TokenParser_Block extends Twig_TokenParser |
---|
13 | { |
---|
14 | /** |
---|
15 | * Parses a token and returns a node. |
---|
16 | * |
---|
17 | * @param Twig_Token $token A Twig_Token instance |
---|
18 | * |
---|
19 | * @return Twig_NodeInterface A Twig_NodeInterface instance |
---|
20 | */ |
---|
21 | public function parse(Twig_Token $token) |
---|
22 | { |
---|
23 | $lineno = $token->getLine(); |
---|
24 | $stream = $this->parser->getStream(); |
---|
25 | $name = $stream->expect(Twig_Token::NAME_TYPE)->getValue(); |
---|
26 | if ($this->parser->hasBlock($name)) { |
---|
27 | throw new Twig_Error_Syntax("The block '$name' has already been defined", $lineno); |
---|
28 | } |
---|
29 | $this->parser->pushLocalScope(); |
---|
30 | $this->parser->pushBlockStack($name); |
---|
31 | |
---|
32 | if ($stream->test(Twig_Token::BLOCK_END_TYPE)) { |
---|
33 | $stream->next(); |
---|
34 | |
---|
35 | $body = $this->parser->subparse(array($this, 'decideBlockEnd'), true); |
---|
36 | if ($stream->test(Twig_Token::NAME_TYPE)) { |
---|
37 | $value = $stream->next()->getValue(); |
---|
38 | |
---|
39 | if ($value != $name) { |
---|
40 | throw new Twig_Error_Syntax(sprintf("Expected endblock for block '$name' (but %s given)", $value), $lineno); |
---|
41 | } |
---|
42 | } |
---|
43 | } else { |
---|
44 | $body = new Twig_Node(array( |
---|
45 | new Twig_Node_Print($this->parser->getExpressionParser()->parseExpression(), $lineno), |
---|
46 | )); |
---|
47 | } |
---|
48 | $stream->expect(Twig_Token::BLOCK_END_TYPE); |
---|
49 | |
---|
50 | $block = new Twig_Node_Block($name, $body, $lineno); |
---|
51 | $this->parser->setBlock($name, $block); |
---|
52 | $this->parser->popBlockStack(); |
---|
53 | $this->parser->popLocalScope(); |
---|
54 | |
---|
55 | return new Twig_Node_BlockReference($name, $lineno, $this->getTag()); |
---|
56 | } |
---|
57 | |
---|
58 | public function decideBlockEnd(Twig_Token $token) |
---|
59 | { |
---|
60 | return $token->test('endblock'); |
---|
61 | } |
---|
62 | |
---|
63 | /** |
---|
64 | * Gets the tag name associated with this token parser. |
---|
65 | * |
---|
66 | * @param string The tag name |
---|
67 | */ |
---|
68 | public function getTag() |
---|
69 | { |
---|
70 | return 'block'; |
---|
71 | } |
---|
72 | } |
---|