[345] | 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_For 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 | $targets = $this->parser->getExpressionParser()->parseAssignmentExpression(); |
---|
| 25 | $this->parser->getStream()->expect(Twig_Token::OPERATOR_TYPE, 'in'); |
---|
| 26 | $seq = $this->parser->getExpressionParser()->parseExpression(); |
---|
| 27 | |
---|
| 28 | $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE); |
---|
| 29 | $body = $this->parser->subparse(array($this, 'decideForFork')); |
---|
| 30 | if ($this->parser->getStream()->next()->getValue() == 'else') { |
---|
| 31 | $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE); |
---|
| 32 | $else = $this->parser->subparse(array($this, 'decideForEnd'), true); |
---|
| 33 | } else { |
---|
| 34 | $else = null; |
---|
| 35 | } |
---|
| 36 | $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE); |
---|
| 37 | |
---|
| 38 | if (count($targets) > 1) { |
---|
| 39 | $keyTarget = $targets->getNode(0); |
---|
| 40 | $valueTarget = $targets->getNode(1); |
---|
| 41 | } else { |
---|
| 42 | $keyTarget = new Twig_Node_Expression_AssignName('_key', $lineno); |
---|
| 43 | $valueTarget = $targets->getNode(0); |
---|
| 44 | } |
---|
| 45 | |
---|
| 46 | return new Twig_Node_For($keyTarget, $valueTarget, $seq, $body, $else, $lineno, $this->getTag()); |
---|
| 47 | } |
---|
| 48 | |
---|
| 49 | public function decideForFork(Twig_Token $token) |
---|
| 50 | { |
---|
| 51 | return $token->test(array('else', 'endfor')); |
---|
| 52 | } |
---|
| 53 | |
---|
| 54 | public function decideForEnd(Twig_Token $token) |
---|
| 55 | { |
---|
| 56 | return $token->test('endfor'); |
---|
| 57 | } |
---|
| 58 | |
---|
| 59 | /** |
---|
| 60 | * Gets the tag name associated with this token parser. |
---|
| 61 | * |
---|
| 62 | * @param string The tag name |
---|
| 63 | */ |
---|
| 64 | public function getTag() |
---|
| 65 | { |
---|
| 66 | return 'for'; |
---|
| 67 | } |
---|
| 68 | } |
---|