blob: fdf92a8e76bc239d6622ad5207d98c8262549ba7 [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 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Twig\Node\Expression;
13
14use Twig\Compiler;
15use Twig\Error\SyntaxError;
16use Twig\Extension\ExtensionInterface;
17use Twig\Node\Node;
18
19abstract class CallExpression extends AbstractExpression
20{
21 private $reflector;
22
23 protected function compileCallable(Compiler $compiler)
24 {
25 $callable = $this->getAttribute('callable');
26
27 $closingParenthesis = false;
28 $isArray = false;
29 if (\is_string($callable) && false === strpos($callable, '::')) {
30 $compiler->raw($callable);
31 } else {
32 list($r, $callable) = $this->reflectCallable($callable);
33 if ($r instanceof \ReflectionMethod && \is_string($callable[0])) {
34 if ($r->isStatic()) {
35 $compiler->raw(sprintf('%s::%s', $callable[0], $callable[1]));
36 } else {
37 $compiler->raw(sprintf('$this->env->getRuntime(\'%s\')->%s', $callable[0], $callable[1]));
38 }
39 } elseif ($r instanceof \ReflectionMethod && $callable[0] instanceof ExtensionInterface) {
40 $class = \get_class($callable[0]);
41 if (!$compiler->getEnvironment()->hasExtension($class)) {
42 // Compile a non-optimized call to trigger a \Twig\Error\RuntimeError, which cannot be a compile-time error
43 $compiler->raw(sprintf('$this->env->getExtension(\'%s\')', $class));
44 } else {
45 $compiler->raw(sprintf('$this->extensions[\'%s\']', ltrim($class, '\\')));
46 }
47
48 $compiler->raw(sprintf('->%s', $callable[1]));
49 } else {
50 $closingParenthesis = true;
51 $isArray = true;
52 $compiler->raw(sprintf('call_user_func_array($this->env->get%s(\'%s\')->getCallable(), ', ucfirst($this->getAttribute('type')), $this->getAttribute('name')));
53 }
54 }
55
56 $this->compileArguments($compiler, $isArray);
57
58 if ($closingParenthesis) {
59 $compiler->raw(')');
60 }
61 }
62
63 protected function compileArguments(Compiler $compiler, $isArray = false): void
64 {
65 $compiler->raw($isArray ? '[' : '(');
66
67 $first = true;
68
69 if ($this->hasAttribute('needs_environment') && $this->getAttribute('needs_environment')) {
70 $compiler->raw('$this->env');
71 $first = false;
72 }
73
74 if ($this->hasAttribute('needs_context') && $this->getAttribute('needs_context')) {
75 if (!$first) {
76 $compiler->raw(', ');
77 }
78 $compiler->raw('$context');
79 $first = false;
80 }
81
82 if ($this->hasAttribute('arguments')) {
83 foreach ($this->getAttribute('arguments') as $argument) {
84 if (!$first) {
85 $compiler->raw(', ');
86 }
87 $compiler->string($argument);
88 $first = false;
89 }
90 }
91
92 if ($this->hasNode('node')) {
93 if (!$first) {
94 $compiler->raw(', ');
95 }
96 $compiler->subcompile($this->getNode('node'));
97 $first = false;
98 }
99
100 if ($this->hasNode('arguments')) {
101 $callable = $this->getAttribute('callable');
102 $arguments = $this->getArguments($callable, $this->getNode('arguments'));
103 foreach ($arguments as $node) {
104 if (!$first) {
105 $compiler->raw(', ');
106 }
107 $compiler->subcompile($node);
108 $first = false;
109 }
110 }
111
112 $compiler->raw($isArray ? ']' : ')');
113 }
114
115 protected function getArguments($callable, $arguments)
116 {
117 $callType = $this->getAttribute('type');
118 $callName = $this->getAttribute('name');
119
120 $parameters = [];
121 $named = false;
122 foreach ($arguments as $name => $node) {
123 if (!\is_int($name)) {
124 $named = true;
125 $name = $this->normalizeName($name);
126 } elseif ($named) {
127 throw new SyntaxError(sprintf('Positional arguments cannot be used after named arguments for %s "%s".', $callType, $callName), $this->getTemplateLine(), $this->getSourceContext());
128 }
129
130 $parameters[$name] = $node;
131 }
132
133 $isVariadic = $this->hasAttribute('is_variadic') && $this->getAttribute('is_variadic');
134 if (!$named && !$isVariadic) {
135 return $parameters;
136 }
137
138 if (!$callable) {
139 if ($named) {
140 $message = sprintf('Named arguments are not supported for %s "%s".', $callType, $callName);
141 } else {
142 $message = sprintf('Arbitrary positional arguments are not supported for %s "%s".', $callType, $callName);
143 }
144
145 throw new \LogicException($message);
146 }
147
148 list($callableParameters, $isPhpVariadic) = $this->getCallableParameters($callable, $isVariadic);
149 $arguments = [];
150 $names = [];
151 $missingArguments = [];
152 $optionalArguments = [];
153 $pos = 0;
154 foreach ($callableParameters as $callableParameter) {
155 $name = $this->normalizeName($callableParameter->name);
156 if (\PHP_VERSION_ID >= 80000 && 'range' === $callable) {
157 if ('start' === $name) {
158 $name = 'low';
159 } elseif ('end' === $name) {
160 $name = 'high';
161 }
162 }
163
164 $names[] = $name;
165
166 if (\array_key_exists($name, $parameters)) {
167 if (\array_key_exists($pos, $parameters)) {
168 throw new SyntaxError(sprintf('Argument "%s" is defined twice for %s "%s".', $name, $callType, $callName), $this->getTemplateLine(), $this->getSourceContext());
169 }
170
171 if (\count($missingArguments)) {
172 throw new SyntaxError(sprintf(
173 'Argument "%s" could not be assigned for %s "%s(%s)" because it is mapped to an internal PHP function which cannot determine default value for optional argument%s "%s".',
174 $name, $callType, $callName, implode(', ', $names), \count($missingArguments) > 1 ? 's' : '', implode('", "', $missingArguments)
175 ), $this->getTemplateLine(), $this->getSourceContext());
176 }
177
178 $arguments = array_merge($arguments, $optionalArguments);
179 $arguments[] = $parameters[$name];
180 unset($parameters[$name]);
181 $optionalArguments = [];
182 } elseif (\array_key_exists($pos, $parameters)) {
183 $arguments = array_merge($arguments, $optionalArguments);
184 $arguments[] = $parameters[$pos];
185 unset($parameters[$pos]);
186 $optionalArguments = [];
187 ++$pos;
188 } elseif ($callableParameter->isDefaultValueAvailable()) {
189 $optionalArguments[] = new ConstantExpression($callableParameter->getDefaultValue(), -1);
190 } elseif ($callableParameter->isOptional()) {
191 if (empty($parameters)) {
192 break;
193 } else {
194 $missingArguments[] = $name;
195 }
196 } else {
197 throw new SyntaxError(sprintf('Value for argument "%s" is required for %s "%s".', $name, $callType, $callName), $this->getTemplateLine(), $this->getSourceContext());
198 }
199 }
200
201 if ($isVariadic) {
202 $arbitraryArguments = $isPhpVariadic ? new VariadicExpression([], -1) : new ArrayExpression([], -1);
203 foreach ($parameters as $key => $value) {
204 if (\is_int($key)) {
205 $arbitraryArguments->addElement($value);
206 } else {
207 $arbitraryArguments->addElement($value, new ConstantExpression($key, -1));
208 }
209 unset($parameters[$key]);
210 }
211
212 if ($arbitraryArguments->count()) {
213 $arguments = array_merge($arguments, $optionalArguments);
214 $arguments[] = $arbitraryArguments;
215 }
216 }
217
218 if (!empty($parameters)) {
219 $unknownParameter = null;
220 foreach ($parameters as $parameter) {
221 if ($parameter instanceof Node) {
222 $unknownParameter = $parameter;
223 break;
224 }
225 }
226
227 throw new SyntaxError(
228 sprintf(
229 'Unknown argument%s "%s" for %s "%s(%s)".',
230 \count($parameters) > 1 ? 's' : '', implode('", "', array_keys($parameters)), $callType, $callName, implode(', ', $names)
231 ),
232 $unknownParameter ? $unknownParameter->getTemplateLine() : $this->getTemplateLine(),
233 $unknownParameter ? $unknownParameter->getSourceContext() : $this->getSourceContext()
234 );
235 }
236
237 return $arguments;
238 }
239
240 protected function normalizeName(string $name): string
241 {
242 return strtolower(preg_replace(['/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'], ['\\1_\\2', '\\1_\\2'], $name));
243 }
244
245 private function getCallableParameters($callable, bool $isVariadic): array
246 {
247 list($r) = $this->reflectCallable($callable);
248 if (null === $r) {
249 return [[], false];
250 }
251
252 $parameters = $r->getParameters();
253 if ($this->hasNode('node')) {
254 array_shift($parameters);
255 }
256 if ($this->hasAttribute('needs_environment') && $this->getAttribute('needs_environment')) {
257 array_shift($parameters);
258 }
259 if ($this->hasAttribute('needs_context') && $this->getAttribute('needs_context')) {
260 array_shift($parameters);
261 }
262 if ($this->hasAttribute('arguments') && null !== $this->getAttribute('arguments')) {
263 foreach ($this->getAttribute('arguments') as $argument) {
264 array_shift($parameters);
265 }
266 }
267 $isPhpVariadic = false;
268 if ($isVariadic) {
269 $argument = end($parameters);
270 $isArray = $argument && $argument->hasType() && 'array' === $argument->getType()->getName();
271 if ($isArray && $argument->isDefaultValueAvailable() && [] === $argument->getDefaultValue()) {
272 array_pop($parameters);
273 } elseif ($argument && $argument->isVariadic()) {
274 array_pop($parameters);
275 $isPhpVariadic = true;
276 } else {
277 $callableName = $r->name;
278 if ($r instanceof \ReflectionMethod) {
279 $callableName = $r->getDeclaringClass()->name.'::'.$callableName;
280 }
281
282 throw new \LogicException(sprintf('The last parameter of "%s" for %s "%s" must be an array with default value, eg. "array $arg = []".', $callableName, $this->getAttribute('type'), $this->getAttribute('name')));
283 }
284 }
285
286 return [$parameters, $isPhpVariadic];
287 }
288
289 private function reflectCallable($callable)
290 {
291 if (null !== $this->reflector) {
292 return $this->reflector;
293 }
294
295 if (\is_array($callable)) {
296 if (!method_exists($callable[0], $callable[1])) {
297 // __call()
298 return [null, []];
299 }
300 $r = new \ReflectionMethod($callable[0], $callable[1]);
301 } elseif (\is_object($callable) && !$callable instanceof \Closure) {
302 $r = new \ReflectionObject($callable);
303 $r = $r->getMethod('__invoke');
304 $callable = [$callable, '__invoke'];
305 } elseif (\is_string($callable) && false !== $pos = strpos($callable, '::')) {
306 $class = substr($callable, 0, $pos);
307 $method = substr($callable, $pos + 2);
308 if (!method_exists($class, $method)) {
309 // __staticCall()
310 return [null, []];
311 }
312 $r = new \ReflectionMethod($callable);
313 $callable = [$class, $method];
314 } else {
315 $r = new \ReflectionFunction($callable);
316 }
317
318 return $this->reflector = [$r, $callable];
319 }
320}