Project

General

Profile

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
 * Marks a section of a template as being reusable.
15
 *
16
 * <pre>
17
 *  {% block head %}
18
 *    <link rel="stylesheet" href="style.css" />
19
 *    <title>{% block title %}{% endblock %} - My Webpage</title>
20
 *  {% endblock %}
21
 * </pre>
22
 */
23
class Twig_TokenParser_Block extends Twig_TokenParser
24
{
25
    /**
26
     * Parses a token and returns a node.
27
     *
28
     * @param Twig_Token $token A Twig_Token instance
29
     *
30
     * @return Twig_NodeInterface A Twig_NodeInterface instance
31
     */
32
    public function parse(Twig_Token $token)
33
    {
34
        $lineno = $token->getLine();
35
        $stream = $this->parser->getStream();
36
        $name = $stream->expect(Twig_Token::NAME_TYPE)->getValue();
37
        if ($this->parser->hasBlock($name)) {
38
            throw new Twig_Error_Syntax(sprintf("The block '$name' has already been defined line %d", $this->parser->getBlock($name)->getLine()), $lineno);
39
        }
40
        $this->parser->setBlock($name, $block = new Twig_Node_Block($name, new Twig_Node(array()), $lineno));
41
        $this->parser->pushLocalScope();
42
        $this->parser->pushBlockStack($name);
43

    
44
        if ($stream->test(Twig_Token::BLOCK_END_TYPE)) {
45
            $stream->next();
46

    
47
            $body = $this->parser->subparse(array($this, 'decideBlockEnd'), true);
48
            if ($stream->test(Twig_Token::NAME_TYPE)) {
49
                $value = $stream->next()->getValue();
50

    
51
                if ($value != $name) {
52
                    throw new Twig_Error_Syntax(sprintf("Expected endblock for block '$name' (but %s given)", $value), $lineno);
53
                }
54
            }
55
        } else {
56
            $body = new Twig_Node(array(
57
                new Twig_Node_Print($this->parser->getExpressionParser()->parseExpression(), $lineno),
58
            ));
59
        }
60
        $stream->expect(Twig_Token::BLOCK_END_TYPE);
61

    
62
        $block->setNode('body', $body);
63
        $this->parser->popBlockStack();
64
        $this->parser->popLocalScope();
65

    
66
        return new Twig_Node_BlockReference($name, $lineno, $this->getTag());
67
    }
68

    
69
    public function decideBlockEnd(Twig_Token $token)
70
    {
71
        return $token->test('endblock');
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 'block';
82
    }
83
}
(2-2/16)