blob: c3563f01238756ccb96239d548d945250950abf9 [file] [log] [blame]
Matthias Andreas Benkard12a57352021-12-28 18:02:04 +01001<?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
13namespace Twig\Node\Expression;
14
15use Twig\Compiler;
16
17class NameExpression extends AbstractExpression
18{
19 private $specialVars = [
20 '_self' => '$this->getTemplateName()',
21 '_context' => '$context',
22 '_charset' => '$this->env->getCharset()',
23 ];
24
25 public function __construct(string $name, int $lineno)
26 {
27 parent::__construct([], ['name' => $name, 'is_defined_test' => false, 'ignore_strict_check' => false, 'always_defined' => false], $lineno);
28 }
29
30 public function compile(Compiler $compiler): void
31 {
32 $name = $this->getAttribute('name');
33
34 $compiler->addDebugInfo($this);
35
36 if ($this->getAttribute('is_defined_test')) {
37 if ($this->isSpecial()) {
38 $compiler->repr(true);
39 } elseif (\PHP_VERSION_ID >= 70400) {
40 $compiler
41 ->raw('array_key_exists(')
42 ->string($name)
43 ->raw(', $context)')
44 ;
45 } else {
46 $compiler
47 ->raw('(isset($context[')
48 ->string($name)
49 ->raw(']) || array_key_exists(')
50 ->string($name)
51 ->raw(', $context))')
52 ;
53 }
54 } elseif ($this->isSpecial()) {
55 $compiler->raw($this->specialVars[$name]);
56 } elseif ($this->getAttribute('always_defined')) {
57 $compiler
58 ->raw('$context[')
59 ->string($name)
60 ->raw(']')
61 ;
62 } else {
63 if ($this->getAttribute('ignore_strict_check') || !$compiler->getEnvironment()->isStrictVariables()) {
64 $compiler
65 ->raw('($context[')
66 ->string($name)
67 ->raw('] ?? null)')
68 ;
69 } else {
70 $compiler
71 ->raw('(isset($context[')
72 ->string($name)
73 ->raw(']) || array_key_exists(')
74 ->string($name)
75 ->raw(', $context) ? $context[')
76 ->string($name)
77 ->raw('] : (function () { throw new RuntimeError(\'Variable ')
78 ->string($name)
79 ->raw(' does not exist.\', ')
80 ->repr($this->lineno)
81 ->raw(', $this->source); })()')
82 ->raw(')')
83 ;
84 }
85 }
86 }
87
88 public function isSpecial()
89 {
90 return isset($this->specialVars[$this->getAttribute('name')]);
91 }
92
93 public function isSimple()
94 {
95 return !$this->isSpecial() && !$this->getAttribute('is_defined_test');
96 }
97}