Test Failed
Push — master ( 6a1530...bb1f7e )
by Justin
04:13
created

Twig_ExpressionParser::getTest()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 24
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
rs 8.6845
c 0
b 0
f 0
cc 4
eloc 12
nc 4
nop 1
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
 * Parses expressions.
15
 *
16
 * This parser implements a "Precedence climbing" algorithm.
17
 *
18
 * @see http://www.engr.mun.ca/~theo/Misc/exp_parsing.htm
19
 * @see http://en.wikipedia.org/wiki/Operator-precedence_parser
20
 *
21
 * @author Fabien Potencier <[email protected]>
22
 *
23
 * @internal
24
 */
25
class Twig_ExpressionParser
26
{
27
    const OPERATOR_LEFT = 1;
28
    const OPERATOR_RIGHT = 2;
29
30
    private $parser;
31
    private $env;
32
    private $unaryOperators;
33
    private $binaryOperators;
34
35
    public function __construct(Twig_Parser $parser, Twig_Environment $env)
36
    {
37
        $this->parser = $parser;
38
        $this->env = $env;
39
        $this->unaryOperators = $env->getUnaryOperators();
40
        $this->binaryOperators = $env->getBinaryOperators();
41
    }
42
43
    public function parseExpression($precedence = 0)
44
    {
45
        $expr = $this->getPrimary();
46
        $token = $this->parser->getCurrentToken();
47
        while ($this->isBinary($token) && $this->binaryOperators[$token->getValue()]['precedence'] >= $precedence) {
48
            $op = $this->binaryOperators[$token->getValue()];
49
            $this->parser->getStream()->next();
50
51
            if ('is not' === $token->getValue()) {
52
                $expr = $this->parseNotTestExpression($expr);
53
            } elseif ('is' === $token->getValue()) {
54
                $expr = $this->parseTestExpression($expr);
55
            } elseif (isset($op['callable'])) {
56
                $expr = $op['callable']($this->parser, $expr);
57
            } else {
58
                $expr1 = $this->parseExpression(self::OPERATOR_LEFT === $op['associativity'] ? $op['precedence'] + 1 : $op['precedence']);
59
                $class = $op['class'];
60
                $expr = new $class($expr, $expr1, $token->getLine());
61
            }
62
63
            $token = $this->parser->getCurrentToken();
64
        }
65
66
        if (0 === $precedence) {
67
            return $this->parseConditionalExpression($expr);
68
        }
69
70
        return $expr;
71
    }
72
73
    private function getPrimary()
74
    {
75
        $token = $this->parser->getCurrentToken();
76
77
        if ($this->isUnary($token)) {
78
            $operator = $this->unaryOperators[$token->getValue()];
79
            $this->parser->getStream()->next();
80
            $expr = $this->parseExpression($operator['precedence']);
81
            $class = $operator['class'];
82
83
            return $this->parsePostfixExpression(new $class($expr, $token->getLine()));
84
        } elseif ($token->test(Twig_Token::PUNCTUATION_TYPE, '(')) {
85
            $this->parser->getStream()->next();
86
            $expr = $this->parseExpression();
87
            $this->parser->getStream()->expect(Twig_Token::PUNCTUATION_TYPE, ')', 'An opened parenthesis is not properly closed');
88
89
            return $this->parsePostfixExpression($expr);
90
        }
91
92
        return $this->parsePrimaryExpression();
93
    }
94
95
    private function parseConditionalExpression($expr)
96
    {
97
        while ($this->parser->getStream()->nextIf(Twig_Token::PUNCTUATION_TYPE, '?')) {
98
            if (!$this->parser->getStream()->nextIf(Twig_Token::PUNCTUATION_TYPE, ':')) {
99
                $expr2 = $this->parseExpression();
100
                if ($this->parser->getStream()->nextIf(Twig_Token::PUNCTUATION_TYPE, ':')) {
101
                    $expr3 = $this->parseExpression();
102
                } else {
103
                    $expr3 = new Twig_Node_Expression_Constant('', $this->parser->getCurrentToken()->getLine());
104
                }
105
            } else {
106
                $expr2 = $expr;
107
                $expr3 = $this->parseExpression();
108
            }
109
110
            $expr = new Twig_Node_Expression_Conditional($expr, $expr2, $expr3, $this->parser->getCurrentToken()->getLine());
111
        }
112
113
        return $expr;
114
    }
115
116
    private function isUnary(Twig_Token $token)
117
    {
118
        return $token->test(Twig_Token::OPERATOR_TYPE) && isset($this->unaryOperators[$token->getValue()]);
119
    }
120
121
    private function isBinary(Twig_Token $token)
122
    {
123
        return $token->test(Twig_Token::OPERATOR_TYPE) && isset($this->binaryOperators[$token->getValue()]);
124
    }
125
126
    public function parsePrimaryExpression()
127
    {
128
        $token = $this->parser->getCurrentToken();
129
        switch ($token->getType()) {
130
            case Twig_Token::NAME_TYPE:
131
                $this->parser->getStream()->next();
132
                switch ($token->getValue()) {
133
                    case 'true':
134
                    case 'TRUE':
135
                        $node = new Twig_Node_Expression_Constant(true, $token->getLine());
136
                        break;
137
138
                    case 'false':
139
                    case 'FALSE':
140
                        $node = new Twig_Node_Expression_Constant(false, $token->getLine());
141
                        break;
142
143
                    case 'none':
144
                    case 'NONE':
145
                    case 'null':
146
                    case 'NULL':
147
                        $node = new Twig_Node_Expression_Constant(null, $token->getLine());
148
                        break;
149
150
                    default:
151
                        if ('(' === $this->parser->getCurrentToken()->getValue()) {
152
                            $node = $this->getFunctionNode($token->getValue(), $token->getLine());
153
                        } else {
154
                            $node = new Twig_Node_Expression_Name($token->getValue(), $token->getLine());
155
                        }
156
                }
157
                break;
158
159
            case Twig_Token::NUMBER_TYPE:
160
                $this->parser->getStream()->next();
161
                $node = new Twig_Node_Expression_Constant($token->getValue(), $token->getLine());
162
                break;
163
164
            case Twig_Token::STRING_TYPE:
165
            case Twig_Token::INTERPOLATION_START_TYPE:
166
                $node = $this->parseStringExpression();
167
                break;
168
169
            case Twig_Token::OPERATOR_TYPE:
170
                if (preg_match(Twig_Lexer::REGEX_NAME, $token->getValue(), $matches) && $matches[0] == $token->getValue()) {
171
                    // in this context, string operators are variable names
172
                    $this->parser->getStream()->next();
173
                    $node = new Twig_Node_Expression_Name($token->getValue(), $token->getLine());
174
                    break;
175
                } elseif (isset($this->unaryOperators[$token->getValue()])) {
176
                    $class = $this->unaryOperators[$token->getValue()]['class'];
177
178
                    $ref = new ReflectionClass($class);
179
                    $negClass = 'Twig_Node_Expression_Unary_Neg';
180
                    $posClass = 'Twig_Node_Expression_Unary_Pos';
181
                    if (!(in_array($ref->getName(), array($negClass, $posClass)) || $ref->isSubclassOf($negClass) || $ref->isSubclassOf($posClass))) {
182
                        throw new Twig_Error_Syntax(sprintf('Unexpected unary operator "%s".', $token->getValue()), $token->getLine(), $this->parser->getStream()->getSourceContext());
183
                    }
184
185
                    $this->parser->getStream()->next();
186
                    $expr = $this->parsePrimaryExpression();
187
188
                    $node = new $class($expr, $token->getLine());
189
                    break;
190
                }
191
192
                // no break
193
            default:
194
                if ($token->test(Twig_Token::PUNCTUATION_TYPE, '[')) {
195
                    $node = $this->parseArrayExpression();
196
                } elseif ($token->test(Twig_Token::PUNCTUATION_TYPE, '{')) {
197
                    $node = $this->parseHashExpression();
198
                } elseif ($token->test(Twig_Token::OPERATOR_TYPE, '=') && ('==' === $this->parser->getStream()->look(-1)->getValue() || '!=' === $this->parser->getStream()->look(-1)->getValue())) {
199
                    throw new Twig_Error_Syntax(sprintf('Unexpected operator of value "%s". Did you try to use "===" or "!==" for strict comparison? Use "is same as(value)" instead.', $token->getValue()), $token->getLine(), $this->parser->getStream()->getSourceContext());
200
                } else {
201
                    throw new Twig_Error_Syntax(sprintf('Unexpected token "%s" of value "%s".', Twig_Token::typeToEnglish($token->getType()), $token->getValue()), $token->getLine(), $this->parser->getStream()->getSourceContext());
202
                }
203
        }
204
205
        return $this->parsePostfixExpression($node);
206
    }
207
208
    public function parseStringExpression()
209
    {
210
        $stream = $this->parser->getStream();
211
212
        $nodes = array();
213
        // a string cannot be followed by another string in a single expression
214
        $nextCanBeString = true;
215
        while (true) {
216
            if ($nextCanBeString && $token = $stream->nextIf(Twig_Token::STRING_TYPE)) {
217
                $nodes[] = new Twig_Node_Expression_Constant($token->getValue(), $token->getLine());
218
                $nextCanBeString = false;
219
            } elseif ($stream->nextIf(Twig_Token::INTERPOLATION_START_TYPE)) {
220
                $nodes[] = $this->parseExpression();
221
                $stream->expect(Twig_Token::INTERPOLATION_END_TYPE);
222
                $nextCanBeString = true;
223
            } else {
224
                break;
225
            }
226
        }
227
228
        $expr = array_shift($nodes);
229
        foreach ($nodes as $node) {
230
            $expr = new Twig_Node_Expression_Binary_Concat($expr, $node, $node->getTemplateLine());
231
        }
232
233
        return $expr;
234
    }
235
236
    public function parseArrayExpression()
237
    {
238
        $stream = $this->parser->getStream();
239
        $stream->expect(Twig_Token::PUNCTUATION_TYPE, '[', 'An array element was expected');
240
241
        $node = new Twig_Node_Expression_Array(array(), $stream->getCurrent()->getLine());
242
        $first = true;
243
        while (!$stream->test(Twig_Token::PUNCTUATION_TYPE, ']')) {
244
            if (!$first) {
245
                $stream->expect(Twig_Token::PUNCTUATION_TYPE, ',', 'An array element must be followed by a comma');
246
247
                // trailing ,?
248
                if ($stream->test(Twig_Token::PUNCTUATION_TYPE, ']')) {
249
                    break;
250
                }
251
            }
252
            $first = false;
253
254
            $node->addElement($this->parseExpression());
255
        }
256
        $stream->expect(Twig_Token::PUNCTUATION_TYPE, ']', 'An opened array is not properly closed');
257
258
        return $node;
259
    }
260
261
    public function parseHashExpression()
262
    {
263
        $stream = $this->parser->getStream();
264
        $stream->expect(Twig_Token::PUNCTUATION_TYPE, '{', 'A hash element was expected');
265
266
        $node = new Twig_Node_Expression_Array(array(), $stream->getCurrent()->getLine());
267
        $first = true;
268
        while (!$stream->test(Twig_Token::PUNCTUATION_TYPE, '}')) {
269
            if (!$first) {
270
                $stream->expect(Twig_Token::PUNCTUATION_TYPE, ',', 'A hash value must be followed by a comma');
271
272
                // trailing ,?
273
                if ($stream->test(Twig_Token::PUNCTUATION_TYPE, '}')) {
274
                    break;
275
                }
276
            }
277
            $first = false;
278
279
            // a hash key can be:
280
            //
281
            //  * a number -- 12
282
            //  * a string -- 'a'
283
            //  * a name, which is equivalent to a string -- a
284
            //  * an expression, which must be enclosed in parentheses -- (1 + 2)
285
            if (($token = $stream->nextIf(Twig_Token::STRING_TYPE)) || ($token = $stream->nextIf(Twig_Token::NAME_TYPE)) || $token = $stream->nextIf(Twig_Token::NUMBER_TYPE)) {
286
                $key = new Twig_Node_Expression_Constant($token->getValue(), $token->getLine());
287
            } elseif ($stream->test(Twig_Token::PUNCTUATION_TYPE, '(')) {
288
                $key = $this->parseExpression();
289
            } else {
290
                $current = $stream->getCurrent();
291
292
                throw new Twig_Error_Syntax(sprintf('A hash key must be a quoted string, a number, a name, or an expression enclosed in parentheses (unexpected token "%s" of value "%s".', Twig_Token::typeToEnglish($current->getType()), $current->getValue()), $current->getLine(), $stream->getSourceContext());
293
            }
294
295
            $stream->expect(Twig_Token::PUNCTUATION_TYPE, ':', 'A hash key must be followed by a colon (:)');
296
            $value = $this->parseExpression();
297
298
            $node->addElement($value, $key);
299
        }
300
        $stream->expect(Twig_Token::PUNCTUATION_TYPE, '}', 'An opened hash is not properly closed');
301
302
        return $node;
303
    }
304
305
    public function parsePostfixExpression($node)
306
    {
307
        while (true) {
308
            $token = $this->parser->getCurrentToken();
309
            if (Twig_Token::PUNCTUATION_TYPE == $token->getType()) {
310
                if ('.' == $token->getValue() || '[' == $token->getValue()) {
311
                    $node = $this->parseSubscriptExpression($node);
312
                } elseif ('|' == $token->getValue()) {
313
                    $node = $this->parseFilterExpression($node);
314
                } else {
315
                    break;
316
                }
317
            } else {
318
                break;
319
            }
320
        }
321
322
        return $node;
323
    }
324
325
    public function getFunctionNode($name, $line)
326
    {
327
        switch ($name) {
328
            case 'parent':
329
                $this->parseArguments();
330
                if (!count($this->parser->getBlockStack())) {
331
                    throw new Twig_Error_Syntax('Calling "parent" outside a block is forbidden.', $line, $this->parser->getStream()->getSourceContext());
332
                }
333
334
                if (!$this->parser->getParent() && !$this->parser->hasTraits()) {
335
                    throw new Twig_Error_Syntax('Calling "parent" on a template that does not extend nor "use" another template is forbidden.', $line, $this->parser->getStream()->getSourceContext());
336
                }
337
338
                return new Twig_Node_Expression_Parent($this->parser->peekBlockStack(), $line);
339
            case 'block':
340
                $args = $this->parseArguments();
341
                if (count($args) < 1) {
342
                    throw new Twig_Error_Syntax('The "block" function takes one argument (the block name).', $line, $this->parser->getStream()->getSourceContext());
343
                }
344
345
                return new Twig_Node_Expression_BlockReference($args->getNode(0), count($args) > 1 ? $args->getNode(1) : null, $line);
346
            case 'attribute':
347
                $args = $this->parseArguments();
348
                if (count($args) < 2) {
349
                    throw new Twig_Error_Syntax('The "attribute" function takes at least two arguments (the variable and the attributes).', $line, $this->parser->getStream()->getSourceContext());
350
                }
351
352
                return new Twig_Node_Expression_GetAttr($args->getNode(0), $args->getNode(1), count($args) > 2 ? $args->getNode(2) : null, Twig_Template::ANY_CALL, $line);
353
            default:
354
                if (null !== $alias = $this->parser->getImportedSymbol('function', $name)) {
355
                    $arguments = new Twig_Node_Expression_Array(array(), $line);
356
                    foreach ($this->parseArguments() as $n) {
357
                        $arguments->addElement($n);
358
                    }
359
360
                    $node = new Twig_Node_Expression_MethodCall($alias['node'], $alias['name'], $arguments, $line);
361
                    $node->setAttribute('safe', true);
362
363
                    return $node;
364
                }
365
366
                $args = $this->parseArguments(true);
367
                $class = $this->getFunctionNodeClass($name, $line);
368
369
                return new $class($name, $args, $line);
370
        }
371
    }
372
373
    public function parseSubscriptExpression($node)
374
    {
375
        $stream = $this->parser->getStream();
376
        $token = $stream->next();
377
        $lineno = $token->getLine();
378
        $arguments = new Twig_Node_Expression_Array(array(), $lineno);
379
        $type = Twig_Template::ANY_CALL;
380
        if ('.' == $token->getValue()) {
381
            $token = $stream->next();
382
            if (
383
                Twig_Token::NAME_TYPE == $token->getType()
384
                ||
385
                Twig_Token::NUMBER_TYPE == $token->getType()
386
                ||
387
                (Twig_Token::OPERATOR_TYPE == $token->getType() && preg_match(Twig_Lexer::REGEX_NAME, $token->getValue()))
388
            ) {
389
                $arg = new Twig_Node_Expression_Constant($token->getValue(), $lineno);
390
391
                if ($stream->test(Twig_Token::PUNCTUATION_TYPE, '(')) {
392
                    $type = Twig_Template::METHOD_CALL;
393
                    foreach ($this->parseArguments() as $n) {
394
                        $arguments->addElement($n);
395
                    }
396
                }
397
            } else {
398
                throw new Twig_Error_Syntax('Expected name or number.', $lineno, $stream->getSourceContext());
399
            }
400
401
            if ($node instanceof Twig_Node_Expression_Name && null !== $this->parser->getImportedSymbol('template', $node->getAttribute('name'))) {
402
                if (!$arg instanceof Twig_Node_Expression_Constant) {
0 ignored issues
show
introduced by
$arg is always a sub-type of Twig_Node_Expression_Constant.
Loading history...
403
                    throw new Twig_Error_Syntax(sprintf('Dynamic macro names are not supported (called on "%s").', $node->getAttribute('name')), $token->getLine(), $stream->getSourceContext());
404
                }
405
406
                $name = $arg->getAttribute('value');
407
408
                $node = new Twig_Node_Expression_MethodCall($node, 'macro_'.$name, $arguments, $lineno);
409
                $node->setAttribute('safe', true);
410
411
                return $node;
412
            }
413
        } else {
414
            $type = Twig_Template::ARRAY_CALL;
415
416
            // slice?
417
            $slice = false;
418
            if ($stream->test(Twig_Token::PUNCTUATION_TYPE, ':')) {
419
                $slice = true;
420
                $arg = new Twig_Node_Expression_Constant(0, $token->getLine());
421
            } else {
422
                $arg = $this->parseExpression();
423
            }
424
425
            if ($stream->nextIf(Twig_Token::PUNCTUATION_TYPE, ':')) {
426
                $slice = true;
427
            }
428
429
            if ($slice) {
430
                if ($stream->test(Twig_Token::PUNCTUATION_TYPE, ']')) {
431
                    $length = new Twig_Node_Expression_Constant(null, $token->getLine());
432
                } else {
433
                    $length = $this->parseExpression();
434
                }
435
436
                $class = $this->getFilterNodeClass('slice', $token->getLine());
437
                $arguments = new Twig_Node(array($arg, $length));
438
                $filter = new $class($node, new Twig_Node_Expression_Constant('slice', $token->getLine()), $arguments, $token->getLine());
439
440
                $stream->expect(Twig_Token::PUNCTUATION_TYPE, ']');
441
442
                return $filter;
443
            }
444
445
            $stream->expect(Twig_Token::PUNCTUATION_TYPE, ']');
446
        }
447
448
        return new Twig_Node_Expression_GetAttr($node, $arg, $arguments, $type, $lineno);
449
    }
450
451
    public function parseFilterExpression($node)
452
    {
453
        $this->parser->getStream()->next();
454
455
        return $this->parseFilterExpressionRaw($node);
456
    }
457
458
    public function parseFilterExpressionRaw($node, $tag = null)
459
    {
460
        while (true) {
461
            $token = $this->parser->getStream()->expect(Twig_Token::NAME_TYPE);
462
463
            $name = new Twig_Node_Expression_Constant($token->getValue(), $token->getLine());
464
            if (!$this->parser->getStream()->test(Twig_Token::PUNCTUATION_TYPE, '(')) {
465
                $arguments = new Twig_Node();
466
            } else {
467
                $arguments = $this->parseArguments(true);
468
            }
469
470
            $class = $this->getFilterNodeClass($name->getAttribute('value'), $token->getLine());
471
472
            $node = new $class($node, $name, $arguments, $token->getLine(), $tag);
473
474
            if (!$this->parser->getStream()->test(Twig_Token::PUNCTUATION_TYPE, '|')) {
475
                break;
476
            }
477
478
            $this->parser->getStream()->next();
479
        }
480
481
        return $node;
482
    }
483
484
    /**
485
     * Parses arguments.
486
     *
487
     * @param bool $namedArguments Whether to allow named arguments or not
488
     * @param bool $definition     Whether we are parsing arguments for a function definition
489
     *
490
     * @return Twig_Node
491
     *
492
     * @throws Twig_Error_Syntax
493
     */
494
    public function parseArguments($namedArguments = false, $definition = false)
495
    {
496
        $args = array();
497
        $stream = $this->parser->getStream();
498
499
        $stream->expect(Twig_Token::PUNCTUATION_TYPE, '(', 'A list of arguments must begin with an opening parenthesis');
500
        while (!$stream->test(Twig_Token::PUNCTUATION_TYPE, ')')) {
501
            if (!empty($args)) {
502
                $stream->expect(Twig_Token::PUNCTUATION_TYPE, ',', 'Arguments must be separated by a comma');
503
            }
504
505
            if ($definition) {
506
                $token = $stream->expect(Twig_Token::NAME_TYPE, null, 'An argument must be a name');
507
                $value = new Twig_Node_Expression_Name($token->getValue(), $this->parser->getCurrentToken()->getLine());
508
            } else {
509
                $value = $this->parseExpression();
510
            }
511
512
            $name = null;
513
            if ($namedArguments && $token = $stream->nextIf(Twig_Token::OPERATOR_TYPE, '=')) {
514
                if (!$value instanceof Twig_Node_Expression_Name) {
515
                    throw new Twig_Error_Syntax(sprintf('A parameter name must be a string, "%s" given.', get_class($value)), $token->getLine(), $stream->getSourceContext());
516
                }
517
                $name = $value->getAttribute('name');
518
519
                if ($definition) {
520
                    $value = $this->parsePrimaryExpression();
521
522
                    if (!$this->checkConstantExpression($value)) {
523
                        throw new Twig_Error_Syntax(sprintf('A default value for an argument must be a constant (a boolean, a string, a number, or an array).'), $token->getLine(), $stream->getSourceContext());
524
                    }
525
                } else {
526
                    $value = $this->parseExpression();
527
                }
528
            }
529
530
            if ($definition) {
531
                if (null === $name) {
532
                    $name = $value->getAttribute('name');
533
                    $value = new Twig_Node_Expression_Constant(null, $this->parser->getCurrentToken()->getLine());
534
                }
535
                $args[$name] = $value;
536
            } else {
537
                if (null === $name) {
538
                    $args[] = $value;
539
                } else {
540
                    $args[$name] = $value;
541
                }
542
            }
543
        }
544
        $stream->expect(Twig_Token::PUNCTUATION_TYPE, ')', 'A list of arguments must be closed by a parenthesis');
545
546
        return new Twig_Node($args);
547
    }
548
549
    public function parseAssignmentExpression()
550
    {
551
        $stream = $this->parser->getStream();
552
        $targets = array();
553
        while (true) {
554
            $token = $stream->expect(Twig_Token::NAME_TYPE, null, 'Only variables can be assigned to');
555
            $value = $token->getValue();
556
            if (in_array(strtolower($value), array('true', 'false', 'none', 'null'))) {
557
                throw new Twig_Error_Syntax(sprintf('You cannot assign a value to "%s".', $value), $token->getLine(), $stream->getSourceContext());
558
            }
559
            $targets[] = new Twig_Node_Expression_AssignName($value, $token->getLine());
560
561
            if (!$stream->nextIf(Twig_Token::PUNCTUATION_TYPE, ',')) {
562
                break;
563
            }
564
        }
565
566
        return new Twig_Node($targets);
567
    }
568
569
    public function parseMultitargetExpression()
570
    {
571
        $targets = array();
572
        while (true) {
573
            $targets[] = $this->parseExpression();
574
            if (!$this->parser->getStream()->nextIf(Twig_Token::PUNCTUATION_TYPE, ',')) {
575
                break;
576
            }
577
        }
578
579
        return new Twig_Node($targets);
580
    }
581
582
    private function parseNotTestExpression(Twig_Node $node)
583
    {
584
        return new Twig_Node_Expression_Unary_Not($this->parseTestExpression($node), $this->parser->getCurrentToken()->getLine());
585
    }
586
587
    private function parseTestExpression(Twig_Node $node)
588
    {
589
        $stream = $this->parser->getStream();
590
        list($name, $test) = $this->getTest($node->getTemplateLine());
591
592
        $class = $this->getTestNodeClass($test);
593
        $arguments = null;
594
        if ($stream->test(Twig_Token::PUNCTUATION_TYPE, '(')) {
595
            $arguments = $this->parser->getExpressionParser()->parseArguments(true);
596
        }
597
598
        return new $class($node, $name, $arguments, $this->parser->getCurrentToken()->getLine());
599
    }
600
601
    private function getTest($line)
602
    {
603
        $stream = $this->parser->getStream();
604
        $name = $stream->expect(Twig_Token::NAME_TYPE)->getValue();
605
606
        if ($test = $this->env->getTest($name)) {
607
            return array($name, $test);
608
        }
609
610
        if ($stream->test(Twig_Token::NAME_TYPE)) {
611
            // try 2-words tests
612
            $name = $name.' '.$this->parser->getCurrentToken()->getValue();
613
614
            if ($test = $this->env->getTest($name)) {
615
                $stream->next();
616
617
                return array($name, $test);
618
            }
619
        }
620
621
        $e = new Twig_Error_Syntax(sprintf('Unknown "%s" test.', $name), $line, $stream->getSourceContext());
622
        $e->addSuggestions($name, array_keys($this->env->getTests()));
623
624
        throw $e;
625
    }
626
627
    private function getTestNodeClass($test)
628
    {
629
        if ($test->isDeprecated()) {
630
            $stream = $this->parser->getStream();
631
            $message = sprintf('Twig Test "%s" is deprecated', $test->getName());
632
633
            if (!is_bool($test->getDeprecatedVersion())) {
634
                $message .= sprintf(' since version %s', $test->getDeprecatedVersion());
635
            }
636
            if ($test->getAlternative()) {
637
                $message .= sprintf('. Use "%s" instead', $test->getAlternative());
638
            }
639
            $src = $stream->getSourceContext();
640
            $message .= sprintf(' in %s at line %d.', $src->getPath() ?: $src->getName(), $stream->getCurrent()->getLine());
641
642
            @trigger_error($message, E_USER_DEPRECATED);
643
        }
644
645
        return $test->getNodeClass();
646
    }
647
648
    private function getFunctionNodeClass($name, $line)
649
    {
650
        if (false === $function = $this->env->getFunction($name)) {
651
            $e = new Twig_Error_Syntax(sprintf('Unknown "%s" function.', $name), $line, $this->parser->getStream()->getSourceContext());
652
            $e->addSuggestions($name, array_keys($this->env->getFunctions()));
653
654
            throw $e;
655
        }
656
657
        if ($function->isDeprecated()) {
658
            $message = sprintf('Twig Function "%s" is deprecated', $function->getName());
659
            if (!is_bool($function->getDeprecatedVersion())) {
660
                $message .= sprintf(' since version %s', $function->getDeprecatedVersion());
661
            }
662
            if ($function->getAlternative()) {
663
                $message .= sprintf('. Use "%s" instead', $function->getAlternative());
664
            }
665
            $src = $this->parser->getStream()->getSourceContext();
666
            $message .= sprintf(' in %s at line %d.', $src->getPath() ?: $src->getName(), $line);
667
668
            @trigger_error($message, E_USER_DEPRECATED);
669
        }
670
671
        return $function->getNodeClass();
672
    }
673
674
    private function getFilterNodeClass($name, $line)
675
    {
676
        if (false === $filter = $this->env->getFilter($name)) {
677
            $e = new Twig_Error_Syntax(sprintf('Unknown "%s" filter.', $name), $line, $this->parser->getStream()->getSourceContext());
678
            $e->addSuggestions($name, array_keys($this->env->getFilters()));
679
680
            throw $e;
681
        }
682
683
        if ($filter->isDeprecated()) {
684
            $message = sprintf('Twig Filter "%s" is deprecated', $filter->getName());
685
            if (!is_bool($filter->getDeprecatedVersion())) {
686
                $message .= sprintf(' since version %s', $filter->getDeprecatedVersion());
687
            }
688
            if ($filter->getAlternative()) {
689
                $message .= sprintf('. Use "%s" instead', $filter->getAlternative());
690
            }
691
            $src = $this->parser->getStream()->getSourceContext();
692
            $message .= sprintf(' in %s at line %d.', $src->getPath() ?: $src->getName(), $line);
693
694
            @trigger_error($message, E_USER_DEPRECATED);
695
        }
696
697
        return $filter->getNodeClass();
698
    }
699
700
    // checks that the node only contains "constant" elements
701
    private function checkConstantExpression(Twig_Node $node)
702
    {
703
        if (!($node instanceof Twig_Node_Expression_Constant || $node instanceof Twig_Node_Expression_Array
704
            || $node instanceof Twig_Node_Expression_Unary_Neg || $node instanceof Twig_Node_Expression_Unary_Pos
705
        )) {
706
            return false;
707
        }
708
709
        foreach ($node as $n) {
710
            if (!$this->checkConstantExpression($n)) {
711
                return false;
712
            }
713
        }
714
715
        return true;
716
    }
717
}
718
719
class_alias('Twig_ExpressionParser', 'Twig\ExpressionParser', false);
720