1<?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;
13
14use Twig\Error\RuntimeError;
15use Twig\ExpressionParser\ExpressionParsers;
16use Twig\ExpressionParser\Infix\BinaryOperatorExpressionParser;
17use Twig\ExpressionParser\InfixAssociativity;
18use Twig\ExpressionParser\InfixExpressionParserInterface;
19use Twig\ExpressionParser\PrecedenceChange;
20use Twig\ExpressionParser\Prefix\UnaryOperatorExpressionParser;
21use Twig\Extension\AttributeExtension;
22use Twig\Extension\ExtensionInterface;
23use Twig\Extension\GlobalsInterface;
24use Twig\Extension\LastModifiedExtensionInterface;
25use Twig\Extension\StagingExtension;
26use Twig\Node\Expression\AbstractExpression;
27use Twig\NodeVisitor\NodeVisitorInterface;
28use Twig\TokenParser\TokenParserInterface;
29
30// Help opcache.preload discover always-needed symbols
31// @see https://github.com/php/php-src/issues/10131
32class_exists(BinaryOperatorExpressionParser::class);
33
34/**
35 * @author Fabien Potencier <fabien@symfony.com>
36 *
37 * @internal
38 */
39final class ExtensionSet
40{
41    private $extensions;
42    private $initialized = false;
43    private $runtimeInitialized = false;
44    private $staging;
45    private $parsers;
46    private $visitors;
47    /** @var array<string, TwigFilter> */
48    private $filters;
49    /** @var array<string, TwigFilter> */
50    private $dynamicFilters;
51    /** @var array<string, TwigTest> */
52    private $tests;
53    /** @var array<string, TwigTest> */
54    private $dynamicTests;
55    /** @var array<string, TwigFunction> */
56    private $functions;
57    /** @var array<string, TwigFunction> */
58    private $dynamicFunctions;
59    private ExpressionParsers $expressionParsers;
60    /** @var array<string, mixed>|null */
61    private $globals;
62    /** @var array<callable(string): (TwigFunction|false)> */
63    private $functionCallbacks = [];
64    /** @var array<callable(string): (TwigFilter|false)> */
65    private $filterCallbacks = [];
66    /** @var array<callable(string): (TwigTest|false)> */
67    private $testCallbacks = [];
68    /** @var array<callable(string): (TokenParserInterface|false)> */
69    private $parserCallbacks = [];
70    private $lastModified = 0;
71
72    public function __construct()
73    {
74        $this->staging = new StagingExtension();
75    }
76
77    /**
78     * @return void
79     */
80    public function initRuntime()
81    {
82        $this->runtimeInitialized = true;
83    }
84
85    public function hasExtension(string $class): bool
86    {
87        return isset($this->extensions[ltrim($class, '\\')]);
88    }
89
90    public function getExtension(string $class): ExtensionInterface
91    {
92        $class = ltrim($class, '\\');
93
94        if (!isset($this->extensions[$class])) {
95            throw new RuntimeError(\sprintf('The "%s" extension is not enabled.', $class));
96        }
97
98        return $this->extensions[$class];
99    }
100
101    /**
102     * @param ExtensionInterface[] $extensions
103     */
104    public function setExtensions(array $extensions): void
105    {
106        foreach ($extensions as $extension) {
107            $this->addExtension($extension);
108        }
109    }
110
111    /**
112     * @return ExtensionInterface[]
113     */
114    public function getExtensions(): array
115    {
116        return $this->extensions;
117    }
118
119    public function getSignature(): string
120    {
121        return json_encode(array_keys($this->extensions));
122    }
123
124    public function isInitialized(): bool
125    {
126        return $this->initialized || $this->runtimeInitialized;
127    }
128
129    public function getLastModified(): int
130    {
131        if (0 !== $this->lastModified) {
132            return $this->lastModified;
133        }
134
135        $lastModified = 0;
136        foreach ($this->extensions as $extension) {
137            if ($extension instanceof LastModifiedExtensionInterface) {
138                $lastModified = max($extension->getLastModified(), $lastModified);
139            } else {
140                $r = new \ReflectionObject($extension);
141                if (is_file($r->getFileName())) {
142                    $lastModified = max(filemtime($r->getFileName()), $lastModified);
143                }
144            }
145        }
146
147        return $this->lastModified = $lastModified;
148    }
149
150    public function addExtension(ExtensionInterface $extension): void
151    {
152        if ($extension instanceof AttributeExtension) {
153            $class = $extension->getClass();
154        } else {
155            $class = $extension::class;
156        }
157
158        if ($this->initialized) {
159            throw new \LogicException(\sprintf('Unable to register extension "%s" as extensions have already been initialized.', $class));
160        }
161
162        if (isset($this->extensions[$class])) {
163            throw new \LogicException(\sprintf('Unable to register extension "%s" as it is already registered.', $class));
164        }
165
166        $this->extensions[$class] = $extension;
167    }
168
169    public function addFunction(TwigFunction $function): void
170    {
171        if ($this->initialized) {
172            throw new \LogicException(\sprintf('Unable to add function "%s" as extensions have already been initialized.', $function->getName()));
173        }
174
175        $this->staging->addFunction($function);
176    }
177
178    /**
179     * @return TwigFunction[]
180     */
181    public function getFunctions(): array
182    {
183        if (!$this->initialized) {
184            $this->initExtensions();
185        }
186
187        return $this->functions;
188    }
189
190    public function getFunction(string $name): ?TwigFunction
191    {
192        if (!$this->initialized) {
193            $this->initExtensions();
194        }
195
196        if (isset($this->functions[$name])) {
197            return $this->functions[$name];
198        }
199
200        foreach ($this->dynamicFunctions as $pattern => $function) {
201            if (preg_match($pattern, $name, $matches)) {
202                array_shift($matches);
203
204                return $function->withDynamicArguments($name, $function->getName(), $matches);
205            }
206        }
207
208        foreach ($this->functionCallbacks as $callback) {
209            if (false !== $function = $callback($name)) {
210                return $function;
211            }
212        }
213
214        return null;
215    }
216
217    /**
218     * @param callable(string): (TwigFunction|false) $callable
219     */
220    public function registerUndefinedFunctionCallback(callable $callable): void
221    {
222        $this->functionCallbacks[] = $callable;
223    }
224
225    public function addFilter(TwigFilter $filter): void
226    {
227        if ($this->initialized) {
228            throw new \LogicException(\sprintf('Unable to add filter "%s" as extensions have already been initialized.', $filter->getName()));
229        }
230
231        $this->staging->addFilter($filter);
232    }
233
234    /**
235     * @return TwigFilter[]
236     */
237    public function getFilters(): array
238    {
239        if (!$this->initialized) {
240            $this->initExtensions();
241        }
242
243        return $this->filters;
244    }
245
246    public function getFilter(string $name): ?TwigFilter
247    {
248        if (!$this->initialized) {
249            $this->initExtensions();
250        }
251
252        if (isset($this->filters[$name])) {
253            return $this->filters[$name];
254        }
255
256        foreach ($this->dynamicFilters as $pattern => $filter) {
257            if (preg_match($pattern, $name, $matches)) {
258                array_shift($matches);
259
260                return $filter->withDynamicArguments($name, $filter->getName(), $matches);
261            }
262        }
263
264        foreach ($this->filterCallbacks as $callback) {
265            if (false !== $filter = $callback($name)) {
266                return $filter;
267            }
268        }
269
270        return null;
271    }
272
273    /**
274     * @param callable(string): (TwigFilter|false) $callable
275     */
276    public function registerUndefinedFilterCallback(callable $callable): void
277    {
278        $this->filterCallbacks[] = $callable;
279    }
280
281    public function addNodeVisitor(NodeVisitorInterface $visitor): void
282    {
283        if ($this->initialized) {
284            throw new \LogicException('Unable to add a node visitor as extensions have already been initialized.');
285        }
286
287        $this->staging->addNodeVisitor($visitor);
288    }
289
290    /**
291     * @return NodeVisitorInterface[]
292     */
293    public function getNodeVisitors(): array
294    {
295        if (!$this->initialized) {
296            $this->initExtensions();
297        }
298
299        return $this->visitors;
300    }
301
302    public function addTokenParser(TokenParserInterface $parser): void
303    {
304        if ($this->initialized) {
305            throw new \LogicException('Unable to add a token parser as extensions have already been initialized.');
306        }
307
308        $this->staging->addTokenParser($parser);
309    }
310
311    /**
312     * @return TokenParserInterface[]
313     */
314    public function getTokenParsers(): array
315    {
316        if (!$this->initialized) {
317            $this->initExtensions();
318        }
319
320        return $this->parsers;
321    }
322
323    public function getTokenParser(string $name): ?TokenParserInterface
324    {
325        if (!$this->initialized) {
326            $this->initExtensions();
327        }
328
329        if (isset($this->parsers[$name])) {
330            return $this->parsers[$name];
331        }
332
333        foreach ($this->parserCallbacks as $callback) {
334            if (false !== $parser = $callback($name)) {
335                return $parser;
336            }
337        }
338
339        return null;
340    }
341
342    /**
343     * @param callable(string): (TokenParserInterface|false) $callable
344     */
345    public function registerUndefinedTokenParserCallback(callable $callable): void
346    {
347        $this->parserCallbacks[] = $callable;
348    }
349
350    /**
351     * @return array<string, mixed>
352     */
353    public function getGlobals(): array
354    {
355        if (null !== $this->globals) {
356            return $this->globals;
357        }
358
359        $globals = [];
360        foreach ($this->extensions as $extension) {
361            if (!$extension instanceof GlobalsInterface) {
362                continue;
363            }
364
365            $globals = array_merge($globals, $extension->getGlobals());
366        }
367
368        if ($this->initialized) {
369            $this->globals = $globals;
370        }
371
372        return $globals;
373    }
374
375    public function resetGlobals(): void
376    {
377        $this->globals = null;
378    }
379
380    public function addTest(TwigTest $test): void
381    {
382        if ($this->initialized) {
383            throw new \LogicException(\sprintf('Unable to add test "%s" as extensions have already been initialized.', $test->getName()));
384        }
385
386        $this->staging->addTest($test);
387    }
388
389    /**
390     * @return TwigTest[]
391     */
392    public function getTests(): array
393    {
394        if (!$this->initialized) {
395            $this->initExtensions();
396        }
397
398        return $this->tests;
399    }
400
401    public function getTest(string $name): ?TwigTest
402    {
403        if (!$this->initialized) {
404            $this->initExtensions();
405        }
406
407        if (isset($this->tests[$name])) {
408            return $this->tests[$name];
409        }
410
411        foreach ($this->dynamicTests as $pattern => $test) {
412            if (preg_match($pattern, $name, $matches)) {
413                array_shift($matches);
414
415                return $test->withDynamicArguments($name, $test->getName(), $matches);
416            }
417        }
418
419        foreach ($this->testCallbacks as $callback) {
420            if (false !== $test = $callback($name)) {
421                return $test;
422            }
423        }
424
425        return null;
426    }
427
428    /**
429     * @param callable(string): (TwigTest|false) $callable
430     */
431    public function registerUndefinedTestCallback(callable $callable): void
432    {
433        $this->testCallbacks[] = $callable;
434    }
435
436    public function getExpressionParsers(): ExpressionParsers
437    {
438        if (!$this->initialized) {
439            $this->initExtensions();
440        }
441
442        return $this->expressionParsers;
443    }
444
445    private function initExtensions(): void
446    {
447        $this->parsers = [];
448        $this->filters = [];
449        $this->functions = [];
450        $this->tests = [];
451        $this->dynamicFilters = [];
452        $this->dynamicFunctions = [];
453        $this->dynamicTests = [];
454        $this->visitors = [];
455        $this->expressionParsers = new ExpressionParsers();
456
457        foreach ($this->extensions as $extension) {
458            $this->initExtension($extension);
459        }
460        $this->initExtension($this->staging);
461        // Done at the end only, so that an exception during initialization does not mark the environment as initialized when catching the exception
462        $this->initialized = true;
463    }
464
465    private function initExtension(ExtensionInterface $extension): void
466    {
467        // filters
468        foreach ($extension->getFilters() as $filter) {
469            $this->filters[$name = $filter->getName()] = $filter;
470            if (str_contains($name, '*')) {
471                $this->dynamicFilters['#^'.str_replace('\\*', '(.*?)', preg_quote($name, '#')).'$#'] = $filter;
472            }
473        }
474
475        // functions
476        foreach ($extension->getFunctions() as $function) {
477            $this->functions[$name = $function->getName()] = $function;
478            if (str_contains($name, '*')) {
479                $this->dynamicFunctions['#^'.str_replace('\\*', '(.*?)', preg_quote($name, '#')).'$#'] = $function;
480            }
481        }
482
483        // tests
484        foreach ($extension->getTests() as $test) {
485            $this->tests[$name = $test->getName()] = $test;
486            if (str_contains($name, '*')) {
487                $this->dynamicTests['#^'.str_replace('\\*', '(.*?)', preg_quote($name, '#')).'$#'] = $test;
488            }
489        }
490
491        // token parsers
492        foreach ($extension->getTokenParsers() as $parser) {
493            if (!$parser instanceof TokenParserInterface) {
494                throw new \LogicException('getTokenParsers() must return an array of \Twig\TokenParser\TokenParserInterface.');
495            }
496
497            $this->parsers[$parser->getTag()] = $parser;
498        }
499
500        // node visitors
501        foreach ($extension->getNodeVisitors() as $visitor) {
502            $this->visitors[] = $visitor;
503        }
504
505        // expression parsers
506        if (method_exists($extension, 'getExpressionParsers')) {
507            $this->expressionParsers->add($extension->getExpressionParsers());
508        }
509
510        $operators = $extension->getOperators();
511        if (!\is_array($operators)) {
512            throw new \InvalidArgumentException(\sprintf('"%s::getOperators()" must return an array with operators, got "%s".', $extension::class, get_debug_type($operators).(\is_resource($operators) ? '' : '#'.$operators)));
513        }
514
515        if (2 !== \count($operators)) {
516            throw new \InvalidArgumentException(\sprintf('"%s::getOperators()" must return an array of 2 elements, got %d.', $extension::class, \count($operators)));
517        }
518
519        $expressionParsers = [];
520        foreach ($operators[0] as $operator => $op) {
521            $expressionParsers[] = new UnaryOperatorExpressionParser($op['class'], $operator, $op['precedence'], $op['precedence_change'] ?? null, '', $op['aliases'] ?? []);
522        }
523        foreach ($operators[1] as $operator => $op) {
524            $op['associativity'] = match ($op['associativity']) {
525                1 => InfixAssociativity::Left,
526                2 => InfixAssociativity::Right,
527                default => throw new \InvalidArgumentException(\sprintf('Invalid associativity "%s" for operator "%s".', $op['associativity'], $operator)),
528            };
529
530            if (isset($op['callable'])) {
531                $expressionParsers[] = $this->convertInfixExpressionParser($op['class'], $operator, $op['precedence'], $op['associativity'], $op['precedence_change'] ?? null, $op['aliases'] ?? [], $op['callable']);
532            } else {
533                $expressionParsers[] = new BinaryOperatorExpressionParser($op['class'], $operator, $op['precedence'], $op['associativity'], $op['precedence_change'] ?? null, '', $op['aliases'] ?? []);
534            }
535        }
536
537        if (\count($expressionParsers)) {
538            trigger_deprecation('twig/twig', '3.21', \sprintf('Extension "%s" uses the old signature for "getOperators()", please implement "getExpressionParsers()" instead.', $extension::class));
539
540            $this->expressionParsers->add($expressionParsers);
541        }
542    }
543
544    private function convertInfixExpressionParser(string $nodeClass, string $operator, int $precedence, InfixAssociativity $associativity, ?PrecedenceChange $precedenceChange, array $aliases, callable $callable): InfixExpressionParserInterface
545    {
546        trigger_deprecation('twig/twig', '3.21', \sprintf('Using a non-ExpressionParserInterface object to define the "%s" binary operator is deprecated.', $operator));
547
548        return new class($nodeClass, $operator, $precedence, $associativity, $precedenceChange, $aliases, $callable) extends BinaryOperatorExpressionParser {
549            public function __construct(
550                string $nodeClass,
551                string $operator,
552                int $precedence,
553                InfixAssociativity $associativity = InfixAssociativity::Left,
554                ?PrecedenceChange $precedenceChange = null,
555                array $aliases = [],
556                private $callable = null,
557            ) {
558                parent::__construct($nodeClass, $operator, $precedence, $associativity, $precedenceChange, $aliases);
559            }
560
561            public function parse(Parser $parser, AbstractExpression $expr, Token $token): AbstractExpression
562            {
563                return ($this->callable)($parser, $expr);
564            }
565        };
566    }
567}
568