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
 * Represents a macro node.
14
 *
15
 * @package    twig
16
 * @author     Fabien Potencier <fabien@symfony.com>
17
 */
18
class Twig_Node_Macro extends Twig_Node
19
{
20
    public function __construct($name, Twig_NodeInterface $body, Twig_NodeInterface $arguments, $lineno, $tag = null)
21
    {
22
        parent::__construct(array('body' => $body, 'arguments' => $arguments), array('name' => $name), $lineno, $tag);
23
    }
24

    
25
    /**
26
     * Compiles the node to PHP.
27
     *
28
     * @param Twig_Compiler A Twig_Compiler instance
29
     */
30
    public function compile(Twig_Compiler $compiler)
31
    {
32
        $arguments = array();
33
        foreach ($this->getNode('arguments') as $argument) {
34
            $arguments[] = '$_'.$argument->getAttribute('name').' = null';
35
        }
36

    
37
        $compiler
38
            ->addDebugInfo($this)
39
            ->write(sprintf("public function get%s(%s)\n", $this->getAttribute('name'), implode(', ', $arguments)), "{\n")
40
            ->indent()
41
        ;
42

    
43
        if (!count($this->getNode('arguments'))) {
44
            $compiler->write("\$context = \$this->env->getGlobals();\n\n");
45
        } else {
46
            $compiler
47
                ->write("\$context = \$this->env->mergeGlobals(array(\n")
48
                ->indent()
49
            ;
50

    
51
            foreach ($this->getNode('arguments') as $argument) {
52
                $compiler
53
                    ->write('')
54
                    ->string($argument->getAttribute('name'))
55
                    ->raw(' => $_'.$argument->getAttribute('name'))
56
                    ->raw(",\n")
57
                ;
58
            }
59

    
60
            $compiler
61
                ->outdent()
62
                ->write("));\n\n")
63
            ;
64
        }
65

    
66
        $compiler
67
            ->write("\$blocks = array();\n\n")
68
            ->write("ob_start();\n")
69
            ->write("try {\n")
70
            ->indent()
71
            ->subcompile($this->getNode('body'))
72
            ->outdent()
73
            ->write("} catch (Exception \$e) {\n")
74
            ->indent()
75
            ->write("ob_end_clean();\n\n")
76
            ->write("throw \$e;\n")
77
            ->outdent()
78
            ->write("}\n\n")
79
            ->write("return ('' === \$tmp = ob_get_clean()) ? '' : new Twig_Markup(\$tmp, \$this->env->getCharset());\n")
80
            ->outdent()
81
            ->write("}\n\n")
82
        ;
83
    }
84
}
(14-14/23)