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
|
|
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
|
/**
|
29
|
* Parses a token and returns a node.
|
30
|
*
|
31
|
* @param Twig_Token $token A Twig_Token instance
|
32
|
*
|
33
|
* @return Twig_NodeInterface A Twig_NodeInterface instance
|
34
|
*/
|
35
|
public function parse(Twig_Token $token)
|
36
|
{
|
37
|
$lineno = $token->getLine();
|
38
|
$expr = $this->parser->getExpressionParser()->parseExpression();
|
39
|
$this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
|
40
|
$body = $this->parser->subparse(array($this, 'decideIfFork'));
|
41
|
$tests = array($expr, $body);
|
42
|
$else = null;
|
43
|
|
44
|
$end = false;
|
45
|
while (!$end) {
|
46
|
switch ($this->parser->getStream()->next()->getValue()) {
|
47
|
case 'else':
|
48
|
$this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
|
49
|
$else = $this->parser->subparse(array($this, 'decideIfEnd'));
|
50
|
break;
|
51
|
|
52
|
case 'elseif':
|
53
|
$expr = $this->parser->getExpressionParser()->parseExpression();
|
54
|
$this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
|
55
|
$body = $this->parser->subparse(array($this, 'decideIfFork'));
|
56
|
$tests[] = $expr;
|
57
|
$tests[] = $body;
|
58
|
break;
|
59
|
|
60
|
case 'endif':
|
61
|
$end = true;
|
62
|
break;
|
63
|
|
64
|
default:
|
65
|
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);
|
66
|
}
|
67
|
}
|
68
|
|
69
|
$this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
|
70
|
|
71
|
return new Twig_Node_If(new Twig_Node($tests), $else, $lineno, $this->getTag());
|
72
|
}
|
73
|
|
74
|
public function decideIfFork(Twig_Token $token)
|
75
|
{
|
76
|
return $token->test(array('elseif', 'else', 'endif'));
|
77
|
}
|
78
|
|
79
|
public function decideIfEnd(Twig_Token $token)
|
80
|
{
|
81
|
return $token->test(array('endif'));
|
82
|
}
|
83
|
|
84
|
/**
|
85
|
* Gets the tag name associated with this token parser.
|
86
|
*
|
87
|
* @return string The tag name
|
88
|
*/
|
89
|
public function getTag()
|
90
|
{
|
91
|
return 'if';
|
92
|
}
|
93
|
}
|