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_If 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 | $expr = $this->parser->getExpressionParser()->parseExpression(); |
---|
25 | $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE); |
---|
26 | $body = $this->parser->subparse(array($this, 'decideIfFork')); |
---|
27 | $tests = array($expr, $body); |
---|
28 | $else = null; |
---|
29 | |
---|
30 | $end = false; |
---|
31 | while (!$end) { |
---|
32 | switch ($this->parser->getStream()->next()->getValue()) { |
---|
33 | case 'else': |
---|
34 | $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE); |
---|
35 | $else = $this->parser->subparse(array($this, 'decideIfEnd')); |
---|
36 | break; |
---|
37 | |
---|
38 | case 'elseif': |
---|
39 | $expr = $this->parser->getExpressionParser()->parseExpression(); |
---|
40 | $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE); |
---|
41 | $body = $this->parser->subparse(array($this, 'decideIfFork')); |
---|
42 | $tests[] = $expr; |
---|
43 | $tests[] = $body; |
---|
44 | break; |
---|
45 | |
---|
46 | case 'endif': |
---|
47 | $end = true; |
---|
48 | break; |
---|
49 | |
---|
50 | default: |
---|
51 | throw new Twig_Error_Syntax(sprintf('Unexpected end of template. Twig was looking for the following tags "else", "elseif", or "endif" to close the "if" block started at line %d)', $lineno), -1); |
---|
52 | } |
---|
53 | } |
---|
54 | |
---|
55 | $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE); |
---|
56 | |
---|
57 | return new Twig_Node_If(new Twig_Node($tests), $else, $lineno, $this->getTag()); |
---|
58 | } |
---|
59 | |
---|
60 | public function decideIfFork(Twig_Token $token) |
---|
61 | { |
---|
62 | return $token->test(array('elseif', 'else', 'endif')); |
---|
63 | } |
---|
64 | |
---|
65 | public function decideIfEnd(Twig_Token $token) |
---|
66 | { |
---|
67 | return $token->test(array('endif')); |
---|
68 | } |
---|
69 | |
---|
70 | /** |
---|
71 | * Gets the tag name associated with this token parser. |
---|
72 | * |
---|
73 | * @param string The tag name |
---|
74 | */ |
---|
75 | public function getTag() |
---|
76 | { |
---|
77 | return 'if'; |
---|
78 | } |
---|
79 | } |
---|