1 |
2
|
Manuela
|
<?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 |
|
|
|
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 |
|
|
class Twig_TokenParser_If extends Twig_TokenParser
|
27 |
|
|
{
|
28 |
|
|
public function parse(Twig_Token $token)
|
29 |
|
|
{
|
30 |
|
|
$lineno = $token->getLine();
|
31 |
|
|
$expr = $this->parser->getExpressionParser()->parseExpression();
|
32 |
|
|
$stream = $this->parser->getStream();
|
33 |
|
|
$stream->expect(Twig_Token::BLOCK_END_TYPE);
|
34 |
|
|
$body = $this->parser->subparse(array($this, 'decideIfFork'));
|
35 |
|
|
$tests = array($expr, $body);
|
36 |
|
|
$else = null;
|
37 |
|
|
|
38 |
|
|
$end = false;
|
39 |
|
|
while (!$end) {
|
40 |
|
|
switch ($stream->next()->getValue()) {
|
41 |
|
|
case 'else':
|
42 |
|
|
$stream->expect(Twig_Token::BLOCK_END_TYPE);
|
43 |
|
|
$else = $this->parser->subparse(array($this, 'decideIfEnd'));
|
44 |
|
|
break;
|
45 |
|
|
|
46 |
|
|
case 'elseif':
|
47 |
|
|
$expr = $this->parser->getExpressionParser()->parseExpression();
|
48 |
|
|
$stream->expect(Twig_Token::BLOCK_END_TYPE);
|
49 |
|
|
$body = $this->parser->subparse(array($this, 'decideIfFork'));
|
50 |
|
|
$tests[] = $expr;
|
51 |
|
|
$tests[] = $body;
|
52 |
|
|
break;
|
53 |
|
|
|
54 |
|
|
case 'endif':
|
55 |
|
|
$end = true;
|
56 |
|
|
break;
|
57 |
|
|
|
58 |
|
|
default:
|
59 |
|
|
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->getFilename());
|
60 |
|
|
}
|
61 |
|
|
}
|
62 |
|
|
|
63 |
|
|
$stream->expect(Twig_Token::BLOCK_END_TYPE);
|
64 |
|
|
|
65 |
|
|
return new Twig_Node_If(new Twig_Node($tests), $else, $lineno, $this->getTag());
|
66 |
|
|
}
|
67 |
|
|
|
68 |
|
|
public function decideIfFork(Twig_Token $token)
|
69 |
|
|
{
|
70 |
|
|
return $token->test(array('elseif', 'else', 'endif'));
|
71 |
|
|
}
|
72 |
|
|
|
73 |
|
|
public function decideIfEnd(Twig_Token $token)
|
74 |
|
|
{
|
75 |
|
|
return $token->test(array('endif'));
|
76 |
|
|
}
|
77 |
|
|
|
78 |
|
|
public function getTag()
|
79 |
|
|
{
|
80 |
|
|
return 'if';
|
81 |
|
|
}
|
82 |
|
|
}
|