Project

General

Profile

1
<?php
2

    
3
/*
4
 * This file is part of Twig.
5
 *
6
 * (c) 2009 Fabien Potencier
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11

    
12
/**
13
 * Defines a variable.
14
 *
15
 * <pre>
16
 *  {% set foo = 'foo' %}
17
 *
18
 *  {% set foo = [1, 2] %}
19
 *
20
 *  {% set foo = {'foo': 'bar'} %}
21
 *
22
 *  {% set foo = 'foo' ~ 'bar' %}
23
 *
24
 *  {% set foo, bar = 'foo', 'bar' %}
25
 *
26
 *  {% set foo %}Some content{% endset %}
27
 * </pre>
28
 */
29
class Twig_TokenParser_Set extends Twig_TokenParser
30
{
31
    /**
32
     * Parses a token and returns a node.
33
     *
34
     * @param Twig_Token $token A Twig_Token instance
35
     *
36
     * @return Twig_NodeInterface A Twig_NodeInterface instance
37
     */
38
    public function parse(Twig_Token $token)
39
    {
40
        $lineno = $token->getLine();
41
        $stream = $this->parser->getStream();
42
        $names = $this->parser->getExpressionParser()->parseAssignmentExpression();
43

    
44
        $capture = false;
45
        if ($stream->nextIf(Twig_Token::OPERATOR_TYPE, '=')) {
46
            $values = $this->parser->getExpressionParser()->parseMultitargetExpression();
47

    
48
            $stream->expect(Twig_Token::BLOCK_END_TYPE);
49

    
50
            if (count($names) !== count($values)) {
51
                throw new Twig_Error_Syntax("When using set, you must have the same number of variables and assignments.", $stream->getCurrent()->getLine(), $stream->getFilename());
52
            }
53
        } else {
54
            $capture = true;
55

    
56
            if (count($names) > 1) {
57
                throw new Twig_Error_Syntax("When using set with a block, you cannot have a multi-target.", $stream->getCurrent()->getLine(), $stream->getFilename());
58
            }
59

    
60
            $stream->expect(Twig_Token::BLOCK_END_TYPE);
61

    
62
            $values = $this->parser->subparse(array($this, 'decideBlockEnd'), true);
63
            $stream->expect(Twig_Token::BLOCK_END_TYPE);
64
        }
65

    
66
        return new Twig_Node_Set($capture, $names, $values, $lineno, $this->getTag());
67
    }
68

    
69
    public function decideBlockEnd(Twig_Token $token)
70
    {
71
        return $token->test('endset');
72
    }
73

    
74
    /**
75
     * Gets the tag name associated with this token parser.
76
     *
77
     * @return string The tag name
78
     */
79
    public function getTag()
80
    {
81
        return 'set';
82
    }
83
}
(15-15/17)