Version 1
[yaffs-website] / vendor / twig / twig / lib / Twig / Parser.php
1 <?php
2
3 /*
4  * This file is part of Twig.
5  *
6  * (c) Fabien Potencier
7  * (c) 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  * @author Fabien Potencier <fabien@symfony.com>
17  */
18 class Twig_Parser implements Twig_ParserInterface
19 {
20     protected $stack = array();
21     protected $stream;
22     protected $parent;
23     protected $handlers;
24     protected $visitors;
25     protected $expressionParser;
26     protected $blocks;
27     protected $blockStack;
28     protected $macros;
29     protected $env;
30     protected $reservedMacroNames;
31     protected $importedSymbols;
32     protected $traits;
33     protected $embeddedTemplates = array();
34
35     public function __construct(Twig_Environment $env)
36     {
37         $this->env = $env;
38     }
39
40     /**
41      * @deprecated since 1.27 (to be removed in 2.0)
42      */
43     public function getEnvironment()
44     {
45         @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0.', E_USER_DEPRECATED);
46
47         return $this->env;
48     }
49
50     public function getVarName()
51     {
52         return sprintf('__internal_%s', hash('sha256', uniqid(mt_rand(), true), false));
53     }
54
55     /**
56      * @deprecated since 1.27 (to be removed in 2.0). Use $parser->getStream()->getSourceContext()->getPath() instead.
57      */
58     public function getFilename()
59     {
60         @trigger_error(sprintf('The "%s" method is deprecated since version 1.27 and will be removed in 2.0. Use $parser->getStream()->getSourceContext()->getPath() instead.', __METHOD__), E_USER_DEPRECATED);
61
62         return $this->stream->getSourceContext()->getName();
63     }
64
65     public function parse(Twig_TokenStream $stream, $test = null, $dropNeedle = false)
66     {
67         // push all variables into the stack to keep the current state of the parser
68         // using get_object_vars() instead of foreach would lead to https://bugs.php.net/71336
69         // This hack can be removed when min version if PHP 7.0
70         $vars = array();
71         foreach ($this as $k => $v) {
72             $vars[$k] = $v;
73         }
74
75         unset($vars['stack'], $vars['env'], $vars['handlers'], $vars['visitors'], $vars['expressionParser'], $vars['reservedMacroNames']);
76         $this->stack[] = $vars;
77
78         // tag handlers
79         if (null === $this->handlers) {
80             $this->handlers = $this->env->getTokenParsers();
81             $this->handlers->setParser($this);
82         }
83
84         // node visitors
85         if (null === $this->visitors) {
86             $this->visitors = $this->env->getNodeVisitors();
87         }
88
89         if (null === $this->expressionParser) {
90             $this->expressionParser = new Twig_ExpressionParser($this, $this->env);
91         }
92
93         $this->stream = $stream;
94         $this->parent = null;
95         $this->blocks = array();
96         $this->macros = array();
97         $this->traits = array();
98         $this->blockStack = array();
99         $this->importedSymbols = array(array());
100         $this->embeddedTemplates = array();
101
102         try {
103             $body = $this->subparse($test, $dropNeedle);
104
105             if (null !== $this->parent && null === $body = $this->filterBodyNodes($body)) {
106                 $body = new Twig_Node();
107             }
108         } catch (Twig_Error_Syntax $e) {
109             if (!$e->getSourceContext()) {
110                 $e->setSourceContext($this->stream->getSourceContext());
111             }
112
113             if (!$e->getTemplateLine()) {
114                 $e->setTemplateLine($this->stream->getCurrent()->getLine());
115             }
116
117             throw $e;
118         }
119
120         $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, $stream->getSourceContext());
121
122         $traverser = new Twig_NodeTraverser($this->env, $this->visitors);
123
124         $node = $traverser->traverse($node);
125
126         // restore previous stack so previous parse() call can resume working
127         foreach (array_pop($this->stack) as $key => $val) {
128             $this->$key = $val;
129         }
130
131         return $node;
132     }
133
134     public function subparse($test, $dropNeedle = false)
135     {
136         $lineno = $this->getCurrentToken()->getLine();
137         $rv = array();
138         while (!$this->stream->isEOF()) {
139             switch ($this->getCurrentToken()->getType()) {
140                 case Twig_Token::TEXT_TYPE:
141                     $token = $this->stream->next();
142                     $rv[] = new Twig_Node_Text($token->getValue(), $token->getLine());
143                     break;
144
145                 case Twig_Token::VAR_START_TYPE:
146                     $token = $this->stream->next();
147                     $expr = $this->expressionParser->parseExpression();
148                     $this->stream->expect(Twig_Token::VAR_END_TYPE);
149                     $rv[] = new Twig_Node_Print($expr, $token->getLine());
150                     break;
151
152                 case Twig_Token::BLOCK_START_TYPE:
153                     $this->stream->next();
154                     $token = $this->getCurrentToken();
155
156                     if ($token->getType() !== Twig_Token::NAME_TYPE) {
157                         throw new Twig_Error_Syntax('A block must start with a tag name.', $token->getLine(), $this->stream->getSourceContext());
158                     }
159
160                     if (null !== $test && call_user_func($test, $token)) {
161                         if ($dropNeedle) {
162                             $this->stream->next();
163                         }
164
165                         if (1 === count($rv)) {
166                             return $rv[0];
167                         }
168
169                         return new Twig_Node($rv, array(), $lineno);
170                     }
171
172                     $subparser = $this->handlers->getTokenParser($token->getValue());
173                     if (null === $subparser) {
174                         if (null !== $test) {
175                             $e = new Twig_Error_Syntax(sprintf('Unexpected "%s" tag', $token->getValue()), $token->getLine(), $this->stream->getSourceContext());
176
177                             if (is_array($test) && isset($test[0]) && $test[0] instanceof Twig_TokenParserInterface) {
178                                 $e->appendMessage(sprintf(' (expecting closing tag for the "%s" tag defined near line %s).', $test[0]->getTag(), $lineno));
179                             }
180                         } else {
181                             $e = new Twig_Error_Syntax(sprintf('Unknown "%s" tag.', $token->getValue()), $token->getLine(), $this->stream->getSourceContext());
182                             $e->addSuggestions($token->getValue(), array_keys($this->env->getTags()));
183                         }
184
185                         throw $e;
186                     }
187
188                     $this->stream->next();
189
190                     $node = $subparser->parse($token);
191                     if (null !== $node) {
192                         $rv[] = $node;
193                     }
194                     break;
195
196                 default:
197                     throw new Twig_Error_Syntax('Lexer or parser ended up in unsupported state.', $this->getCurrentToken()->getLine(), $this->stream->getSourceContext());
198             }
199         }
200
201         if (1 === count($rv)) {
202             return $rv[0];
203         }
204
205         return new Twig_Node($rv, array(), $lineno);
206     }
207
208     /**
209      * @deprecated since 1.27 (to be removed in 2.0)
210      */
211     public function addHandler($name, $class)
212     {
213         @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0.', E_USER_DEPRECATED);
214
215         $this->handlers[$name] = $class;
216     }
217
218     /**
219      * @deprecated since 1.27 (to be removed in 2.0)
220      */
221     public function addNodeVisitor(Twig_NodeVisitorInterface $visitor)
222     {
223         @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0.', E_USER_DEPRECATED);
224
225         $this->visitors[] = $visitor;
226     }
227
228     public function getBlockStack()
229     {
230         return $this->blockStack;
231     }
232
233     public function peekBlockStack()
234     {
235         return $this->blockStack[count($this->blockStack) - 1];
236     }
237
238     public function popBlockStack()
239     {
240         array_pop($this->blockStack);
241     }
242
243     public function pushBlockStack($name)
244     {
245         $this->blockStack[] = $name;
246     }
247
248     public function hasBlock($name)
249     {
250         return isset($this->blocks[$name]);
251     }
252
253     public function getBlock($name)
254     {
255         return $this->blocks[$name];
256     }
257
258     public function setBlock($name, Twig_Node_Block $value)
259     {
260         $this->blocks[$name] = new Twig_Node_Body(array($value), array(), $value->getTemplateLine());
261     }
262
263     public function hasMacro($name)
264     {
265         return isset($this->macros[$name]);
266     }
267
268     public function setMacro($name, Twig_Node_Macro $node)
269     {
270         if ($this->isReservedMacroName($name)) {
271             throw new Twig_Error_Syntax(sprintf('"%s" cannot be used as a macro name as it is a reserved keyword.', $name), $node->getTemplateLine(), $this->stream->getSourceContext());
272         }
273
274         $this->macros[$name] = $node;
275     }
276
277     public function isReservedMacroName($name)
278     {
279         if (null === $this->reservedMacroNames) {
280             $this->reservedMacroNames = array();
281             $r = new ReflectionClass($this->env->getBaseTemplateClass());
282             foreach ($r->getMethods() as $method) {
283                 $methodName = strtolower($method->getName());
284
285                 if ('get' === substr($methodName, 0, 3) && isset($methodName[3])) {
286                     $this->reservedMacroNames[] = substr($methodName, 3);
287                 }
288             }
289         }
290
291         return in_array(strtolower($name), $this->reservedMacroNames);
292     }
293
294     public function addTrait($trait)
295     {
296         $this->traits[] = $trait;
297     }
298
299     public function hasTraits()
300     {
301         return count($this->traits) > 0;
302     }
303
304     public function embedTemplate(Twig_Node_Module $template)
305     {
306         $template->setIndex(mt_rand());
307
308         $this->embeddedTemplates[] = $template;
309     }
310
311     public function addImportedSymbol($type, $alias, $name = null, Twig_Node_Expression $node = null)
312     {
313         $this->importedSymbols[0][$type][$alias] = array('name' => $name, 'node' => $node);
314     }
315
316     public function getImportedSymbol($type, $alias)
317     {
318         foreach ($this->importedSymbols as $functions) {
319             if (isset($functions[$type][$alias])) {
320                 return $functions[$type][$alias];
321             }
322         }
323     }
324
325     public function isMainScope()
326     {
327         return 1 === count($this->importedSymbols);
328     }
329
330     public function pushLocalScope()
331     {
332         array_unshift($this->importedSymbols, array());
333     }
334
335     public function popLocalScope()
336     {
337         array_shift($this->importedSymbols);
338     }
339
340     /**
341      * @return Twig_ExpressionParser
342      */
343     public function getExpressionParser()
344     {
345         return $this->expressionParser;
346     }
347
348     public function getParent()
349     {
350         return $this->parent;
351     }
352
353     public function setParent($parent)
354     {
355         $this->parent = $parent;
356     }
357
358     /**
359      * @return Twig_TokenStream
360      */
361     public function getStream()
362     {
363         return $this->stream;
364     }
365
366     /**
367      * @return Twig_Token
368      */
369     public function getCurrentToken()
370     {
371         return $this->stream->getCurrent();
372     }
373
374     protected function filterBodyNodes(Twig_NodeInterface $node)
375     {
376         // check that the body does not contain non-empty output nodes
377         if (
378             ($node instanceof Twig_Node_Text && !ctype_space($node->getAttribute('data')))
379             ||
380             (!$node instanceof Twig_Node_Text && !$node instanceof Twig_Node_BlockReference && $node instanceof Twig_NodeOutputInterface)
381         ) {
382             if (false !== strpos((string) $node, chr(0xEF).chr(0xBB).chr(0xBF))) {
383                 throw new Twig_Error_Syntax('A template that extends another one cannot start with a byte order mark (BOM); it must be removed.', $node->getTemplateLine(), $this->stream->getSourceContext());
384             }
385
386             throw new Twig_Error_Syntax('A template that extends another one cannot include contents outside Twig blocks. Did you forget to put the contents inside a {% block %} tag?', $node->getTemplateLine(), $this->stream->getSourceContext());
387         }
388
389         // bypass nodes that will "capture" the output
390         if ($node instanceof Twig_NodeCaptureInterface) {
391             return $node;
392         }
393
394         if ($node instanceof Twig_NodeOutputInterface) {
395             return;
396         }
397
398         foreach ($node as $k => $n) {
399             if (null !== $n && null === $this->filterBodyNodes($n)) {
400                 $node->removeNode($k);
401             }
402         }
403
404         return $node;
405     }
406 }