vendor/twig/twig/src/ExtensionSet.php line 475

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