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
 * Default parser implementation.
15
 *
16
 * @package twig
17
 * @author  Fabien Potencier <fabien@symfony.com>
18
 */
19
class Twig_Parser implements Twig_ParserInterface
20
{
21
    protected $stack = array();
22
    protected $stream;
23
    protected $parent;
24
    protected $handlers;
25
    protected $visitors;
26
    protected $expressionParser;
27
    protected $blocks;
28
    protected $blockStack;
29
    protected $macros;
30
    protected $env;
31
    protected $reservedMacroNames;
32
    protected $importedSymbols;
33
    protected $traits;
34
    protected $embeddedTemplates = array();
35

    
36
    /**
37
     * Constructor.
38
     *
39
     * @param Twig_Environment $env A Twig_Environment instance
40
     */
41
    public function __construct(Twig_Environment $env)
42
    {
43
        $this->env = $env;
44
    }
45

    
46
    public function getEnvironment()
47
    {
48
        return $this->env;
49
    }
50

    
51
    public function getVarName()
52
    {
53
        return sprintf('__internal_%s', hash('sha1', uniqid(mt_rand(), true), false));
54
    }
55

    
56
    public function getFilename()
57
    {
58
        return $this->stream->getFilename();
59
    }
60

    
61
    /**
62
     * Converts a token stream to a node tree.
63
     *
64
     * @param Twig_TokenStream $stream A token stream instance
65
     *
66
     * @return Twig_Node_Module A node tree
67
     */
68
    public function parse(Twig_TokenStream $stream, $test = null, $dropNeedle = false)
69
    {
70
        // push all variables into the stack to keep the current state of the parser
71
        $vars = get_object_vars($this);
72
        unset($vars['stack'], $vars['env'], $vars['handlers'], $vars['visitors'], $vars['expressionParser']);
73
        $this->stack[] = $vars;
74

    
75
        // tag handlers
76
        if (null === $this->handlers) {
77
            $this->handlers = $this->env->getTokenParsers();
78
            $this->handlers->setParser($this);
79
        }
80

    
81
        // node visitors
82
        if (null === $this->visitors) {
83
            $this->visitors = $this->env->getNodeVisitors();
84
        }
85

    
86
        if (null === $this->expressionParser) {
87
            $this->expressionParser = new Twig_ExpressionParser($this, $this->env->getUnaryOperators(), $this->env->getBinaryOperators());
88
        }
89

    
90
        $this->stream = $stream;
91
        $this->parent = null;
92
        $this->blocks = array();
93
        $this->macros = array();
94
        $this->traits = array();
95
        $this->blockStack = array();
96
        $this->importedSymbols = array(array());
97
        $this->embeddedTemplates = array();
98

    
99
        try {
100
            $body = $this->subparse($test, $dropNeedle);
101

    
102
            if (null !== $this->parent) {
103
                if (null === $body = $this->filterBodyNodes($body)) {
104
                    $body = new Twig_Node();
105
                }
106
            }
107
        } catch (Twig_Error_Syntax $e) {
108
            if (!$e->getTemplateFile()) {
109
                $e->setTemplateFile($this->getFilename());
110
            }
111

    
112
            if (!$e->getTemplateLine()) {
113
                $e->setTemplateLine($this->stream->getCurrent()->getLine());
114
            }
115

    
116
            throw $e;
117
        }
118

    
119
        $node = new Twig_Node_Module(new Twig_Node_Body(array($body)), $this->parent, new Twig_Node($this->blocks), new Twig_Node($this->macros), new Twig_Node($this->traits), $this->embeddedTemplates, $this->getFilename());
120

    
121
        $traverser = new Twig_NodeTraverser($this->env, $this->visitors);
122

    
123
        $node = $traverser->traverse($node);
124

    
125
        // restore previous stack so previous parse() call can resume working
126
        foreach (array_pop($this->stack) as $key => $val) {
127
            $this->$key = $val;
128
        }
129

    
130
        return $node;
131
    }
132

    
133
    public function subparse($test, $dropNeedle = false)
134
    {
135
        $lineno = $this->getCurrentToken()->getLine();
136
        $rv = array();
137
        while (!$this->stream->isEOF()) {
138
            switch ($this->getCurrentToken()->getType()) {
139
                case Twig_Token::TEXT_TYPE:
140
                    $token = $this->stream->next();
141
                    $rv[] = new Twig_Node_Text($token->getValue(), $token->getLine());
142
                    break;
143

    
144
                case Twig_Token::VAR_START_TYPE:
145
                    $token = $this->stream->next();
146
                    $expr = $this->expressionParser->parseExpression();
147
                    $this->stream->expect(Twig_Token::VAR_END_TYPE);
148
                    $rv[] = new Twig_Node_Print($expr, $token->getLine());
149
                    break;
150

    
151
                case Twig_Token::BLOCK_START_TYPE:
152
                    $this->stream->next();
153
                    $token = $this->getCurrentToken();
154

    
155
                    if ($token->getType() !== Twig_Token::NAME_TYPE) {
156
                        throw new Twig_Error_Syntax('A block must start with a tag name', $token->getLine(), $this->getFilename());
157
                    }
158

    
159
                    if (null !== $test && call_user_func($test, $token)) {
160
                        if ($dropNeedle) {
161
                            $this->stream->next();
162
                        }
163

    
164
                        if (1 === count($rv)) {
165
                            return $rv[0];
166
                        }
167

    
168
                        return new Twig_Node($rv, array(), $lineno);
169
                    }
170

    
171
                    $subparser = $this->handlers->getTokenParser($token->getValue());
172
                    if (null === $subparser) {
173
                        if (null !== $test) {
174
                            $error = sprintf('Unexpected tag name "%s"', $token->getValue());
175
                            if (is_array($test) && isset($test[0]) && $test[0] instanceof Twig_TokenParserInterface) {
176
                                $error .= sprintf(' (expecting closing tag for the "%s" tag defined near line %s)', $test[0]->getTag(), $lineno);
177
                            }
178

    
179
                            throw new Twig_Error_Syntax($error, $token->getLine(), $this->getFilename());
180
                        }
181

    
182
                        $message = sprintf('Unknown tag name "%s"', $token->getValue());
183
                        if ($alternatives = $this->env->computeAlternatives($token->getValue(), array_keys($this->env->getTags()))) {
184
                            $message = sprintf('%s. Did you mean "%s"', $message, implode('", "', $alternatives));
185
                        }
186

    
187
                        throw new Twig_Error_Syntax($message, $token->getLine(), $this->getFilename());
188
                    }
189

    
190
                    $this->stream->next();
191

    
192
                    $node = $subparser->parse($token);
193
                    if (null !== $node) {
194
                        $rv[] = $node;
195
                    }
196
                    break;
197

    
198
                default:
199
                    throw new Twig_Error_Syntax('Lexer or parser ended up in unsupported state.', 0, $this->getFilename());
200
            }
201
        }
202

    
203
        if (1 === count($rv)) {
204
            return $rv[0];
205
        }
206

    
207
        return new Twig_Node($rv, array(), $lineno);
208
    }
209

    
210
    public function addHandler($name, $class)
211
    {
212
        $this->handlers[$name] = $class;
213
    }
214

    
215
    public function addNodeVisitor(Twig_NodeVisitorInterface $visitor)
216
    {
217
        $this->visitors[] = $visitor;
218
    }
219

    
220
    public function getBlockStack()
221
    {
222
        return $this->blockStack;
223
    }
224

    
225
    public function peekBlockStack()
226
    {
227
        return $this->blockStack[count($this->blockStack) - 1];
228
    }
229

    
230
    public function popBlockStack()
231
    {
232
        array_pop($this->blockStack);
233
    }
234

    
235
    public function pushBlockStack($name)
236
    {
237
        $this->blockStack[] = $name;
238
    }
239

    
240
    public function hasBlock($name)
241
    {
242
        return isset($this->blocks[$name]);
243
    }
244

    
245
    public function getBlock($name)
246
    {
247
        return $this->blocks[$name];
248
    }
249

    
250
    public function setBlock($name, $value)
251
    {
252
        $this->blocks[$name] = new Twig_Node_Body(array($value), array(), $value->getLine());
253
    }
254

    
255
    public function hasMacro($name)
256
    {
257
        return isset($this->macros[$name]);
258
    }
259

    
260
    public function setMacro($name, Twig_Node_Macro $node)
261
    {
262
        if (null === $this->reservedMacroNames) {
263
            $this->reservedMacroNames = array();
264
            $r = new ReflectionClass($this->env->getBaseTemplateClass());
265
            foreach ($r->getMethods() as $method) {
266
                $this->reservedMacroNames[] = $method->getName();
267
            }
268
        }
269

    
270
        if (in_array($name, $this->reservedMacroNames)) {
271
            throw new Twig_Error_Syntax(sprintf('"%s" cannot be used as a macro name as it is a reserved keyword', $name), $node->getLine(), $this->getFilename());
272
        }
273

    
274
        $this->macros[$name] = $node;
275
    }
276

    
277
    public function addTrait($trait)
278
    {
279
        $this->traits[] = $trait;
280
    }
281

    
282
    public function hasTraits()
283
    {
284
        return count($this->traits) > 0;
285
    }
286

    
287
    public function embedTemplate(Twig_Node_Module $template)
288
    {
289
        $template->setIndex(mt_rand());
290

    
291
        $this->embeddedTemplates[] = $template;
292
    }
293

    
294
    public function addImportedSymbol($type, $alias, $name = null, Twig_Node_Expression $node = null)
295
    {
296
        $this->importedSymbols[0][$type][$alias] = array('name' => $name, 'node' => $node);
297
    }
298

    
299
    public function getImportedSymbol($type, $alias)
300
    {
301
        foreach ($this->importedSymbols as $functions) {
302
            if (isset($functions[$type][$alias])) {
303
                return $functions[$type][$alias];
304
            }
305
        }
306
    }
307

    
308
    public function isMainScope()
309
    {
310
        return 1 === count($this->importedSymbols);
311
    }
312

    
313
    public function pushLocalScope()
314
    {
315
        array_unshift($this->importedSymbols, array());
316
    }
317

    
318
    public function popLocalScope()
319
    {
320
        array_shift($this->importedSymbols);
321
    }
322

    
323
    /**
324
     * Gets the expression parser.
325
     *
326
     * @return Twig_ExpressionParser The expression parser
327
     */
328
    public function getExpressionParser()
329
    {
330
        return $this->expressionParser;
331
    }
332

    
333
    public function getParent()
334
    {
335
        return $this->parent;
336
    }
337

    
338
    public function setParent($parent)
339
    {
340
        $this->parent = $parent;
341
    }
342

    
343
    /**
344
     * Gets the token stream.
345
     *
346
     * @return Twig_TokenStream The token stream
347
     */
348
    public function getStream()
349
    {
350
        return $this->stream;
351
    }
352

    
353
    /**
354
     * Gets the current token.
355
     *
356
     * @return Twig_Token The current token
357
     */
358
    public function getCurrentToken()
359
    {
360
        return $this->stream->getCurrent();
361
    }
362

    
363
    protected function filterBodyNodes(Twig_NodeInterface $node)
364
    {
365
        // check that the body does not contain non-empty output nodes
366
        if (
367
            ($node instanceof Twig_Node_Text && !ctype_space($node->getAttribute('data')))
368
            ||
369
            (!$node instanceof Twig_Node_Text && !$node instanceof Twig_Node_BlockReference && $node instanceof Twig_NodeOutputInterface)
370
        ) {
371
            if (false !== strpos((string) $node, chr(0xEF).chr(0xBB).chr(0xBF))) {
372
                throw new Twig_Error_Syntax('A template that extends another one cannot have a body but a byte order mark (BOM) has been detected; it must be removed.', $node->getLine(), $this->getFilename());
373
            }
374

    
375
            throw new Twig_Error_Syntax('A template that extends another one cannot have a body.', $node->getLine(), $this->getFilename());
376
        }
377

    
378
        // bypass "set" nodes as they "capture" the output
379
        if ($node instanceof Twig_Node_Set) {
380
            return $node;
381
        }
382

    
383
        if ($node instanceof Twig_NodeOutputInterface) {
384
            return;
385
        }
386

    
387
        foreach ($node as $k => $n) {
388
            if (null !== $n && null === $n = $this->filterBodyNodes($n)) {
389
                $node->removeNode($k);
390
            }
391
        }
392

    
393
        return $node;
394
    }
395
}
(24-24/34)