05459408f0e4d11c9c909c30bcd504a7ea42427f
[yaffs-website] / vendor / twig / twig / lib / Twig / TokenParser / If.php
1 <?php
2
3 /*
4  * This file is part of Twig.
5  *
6  * (c) Fabien Potencier
7  * (c) 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
13 /**
14  * Tests a condition.
15  *
16  * <pre>
17  * {% if users %}
18  *  <ul>
19  *    {% for user in users %}
20  *      <li>{{ user.username|e }}</li>
21  *    {% endfor %}
22  *  </ul>
23  * {% endif %}
24  * </pre>
25  *
26  * @final
27  */
28 class Twig_TokenParser_If extends Twig_TokenParser
29 {
30     public function parse(Twig_Token $token)
31     {
32         $lineno = $token->getLine();
33         $expr = $this->parser->getExpressionParser()->parseExpression();
34         $stream = $this->parser->getStream();
35         $stream->expect(Twig_Token::BLOCK_END_TYPE);
36         $body = $this->parser->subparse(array($this, 'decideIfFork'));
37         $tests = array($expr, $body);
38         $else = null;
39
40         $end = false;
41         while (!$end) {
42             switch ($stream->next()->getValue()) {
43                 case 'else':
44                     $stream->expect(Twig_Token::BLOCK_END_TYPE);
45                     $else = $this->parser->subparse(array($this, 'decideIfEnd'));
46                     break;
47
48                 case 'elseif':
49                     $expr = $this->parser->getExpressionParser()->parseExpression();
50                     $stream->expect(Twig_Token::BLOCK_END_TYPE);
51                     $body = $this->parser->subparse(array($this, 'decideIfFork'));
52                     $tests[] = $expr;
53                     $tests[] = $body;
54                     break;
55
56                 case 'endif':
57                     $end = true;
58                     break;
59
60                 default:
61                     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), $stream->getCurrent()->getLine(), $stream->getSourceContext());
62             }
63         }
64
65         $stream->expect(Twig_Token::BLOCK_END_TYPE);
66
67         return new Twig_Node_If(new Twig_Node($tests), $else, $lineno, $this->getTag());
68     }
69
70     public function decideIfFork(Twig_Token $token)
71     {
72         return $token->test(array('elseif', 'else', 'endif'));
73     }
74
75     public function decideIfEnd(Twig_Token $token)
76     {
77         return $token->test(array('endif'));
78     }
79
80     public function getTag()
81     {
82         return 'if';
83     }
84 }