vendor/twig/twig/src/Environment.php line 353

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\Cache\CacheInterface;
  12. use Twig\Cache\FilesystemCache;
  13. use Twig\Cache\NullCache;
  14. use Twig\Cache\RemovableCacheInterface;
  15. use Twig\Error\Error;
  16. use Twig\Error\LoaderError;
  17. use Twig\Error\RuntimeError;
  18. use Twig\Error\SyntaxError;
  19. use Twig\ExpressionParser\ExpressionParsers;
  20. use Twig\Extension\AttributeExtension;
  21. use Twig\Extension\CoreExtension;
  22. use Twig\Extension\EscaperExtension;
  23. use Twig\Extension\ExtensionInterface;
  24. use Twig\Extension\OptimizerExtension;
  25. use Twig\Extension\SandboxExtension;
  26. use Twig\Extension\YieldNotReadyExtension;
  27. use Twig\Loader\ArrayLoader;
  28. use Twig\Loader\ChainLoader;
  29. use Twig\Loader\LoaderInterface;
  30. use Twig\Node\ModuleNode;
  31. use Twig\Node\Node;
  32. use Twig\NodeVisitor\NodeVisitorInterface;
  33. use Twig\Runtime\EscaperRuntime;
  34. use Twig\RuntimeLoader\FactoryRuntimeLoader;
  35. use Twig\RuntimeLoader\RuntimeLoaderInterface;
  36. use Twig\TokenParser\TokenParserInterface;
  37. /**
  38.  * Stores the Twig configuration and renders templates.
  39.  *
  40.  * @author Fabien Potencier <[email protected]>
  41.  */
  42. class Environment
  43. {
  44.     public const VERSION = '3.31.1';
  45.     public const VERSION_ID = 33101;
  46.     public const MAJOR_VERSION = 3;
  47.     public const MINOR_VERSION = 31;
  48.     public const RELEASE_VERSION = 1;
  49.     public const EXTRA_VERSION = '';
  50.     private $charset;
  51.     private $loader;
  52.     private $debug;
  53.     private $autoReload;
  54.     private $cache;
  55.     private $lexer;
  56.     private $parser;
  57.     private $compiler;
  58.     /** @var array<string, mixed> */
  59.     private $globals = [];
  60.     private $resolvedGlobals;
  61.     private $loadedTemplates;
  62.     private $strictVariables;
  63.     private $originalCache;
  64.     private $extensionSet;
  65.     private $runtimeLoaders = [];
  66.     private $runtimes = [];
  67.     private $optionsHash;
  68.     /** @var bool */
  69.     private $useYield;
  70.     private int $optimizations;
  71.     private $defaultRuntimeLoader;
  72.     private array $hotCache = [];
  73.     /**
  74.      * @var array<string, TemplateWrapper>
  75.      */
  76.     private array $loadedWrappers = [];
  77.     /**
  78.      * Constructor.
  79.      *
  80.      * Available options:
  81.      *
  82.      *  * debug: When set to true, it automatically set "auto_reload" to true as
  83.      *           well (default to false).
  84.      *
  85.      *  * charset: The charset used by the templates (default to UTF-8).
  86.      *
  87.      *  * cache: An absolute path where to store the compiled templates,
  88.      *           a \Twig\Cache\CacheInterface implementation,
  89.      *           or false to disable compilation cache (default).
  90.      *
  91.      *  * auto_reload: Whether to reload the template if the original source changed.
  92.      *                 If you don't provide the auto_reload option, it will be
  93.      *                 determined automatically based on the debug value.
  94.      *
  95.      *  * strict_variables: Whether to ignore invalid variables in templates
  96.      *                      (default to false).
  97.      *
  98.      *  * autoescape: Whether to enable auto-escaping (default to html):
  99.      *                  * false: disable auto-escaping
  100.      *                  * html, js: set the autoescaping to one of the supported strategies
  101.      *                  * name: set the autoescaping strategy based on the template name extension
  102.      *                  * PHP callback: a PHP callback that returns an escaping strategy based on the template "name"
  103.      *
  104.      *  * optimizations: A flag that indicates which optimizations to apply
  105.      *                   (default to -1 which means that all optimizations are enabled;
  106.      *                   set it to 0 to disable).
  107.      *
  108.      *  * use_yield: true: forces templates to exclusively use "yield" instead of "echo" (all extensions must be yield ready)
  109.      *               false (default): allows templates to use a mix of "yield" and "echo" calls to allow for a progressive migration
  110.      *               Switch to "true" when possible as this will be the only supported mode in Twig 4.0
  111.      */
  112.     public function __construct(LoaderInterface $loader, array $options = [])
  113.     {
  114.         $this->setLoader($loader);
  115.         $options = array_merge([
  116.             'debug' => false,
  117.             'charset' => 'UTF-8',
  118.             'strict_variables' => false,
  119.             'autoescape' => 'html',
  120.             'cache' => false,
  121.             'auto_reload' => null,
  122.             'optimizations' => -1,
  123.             'use_yield' => false,
  124.         ], $options);
  125.         $this->useYield = (bool) $options['use_yield'];
  126.         $this->optimizations = (int) $options['optimizations'];
  127.         $this->debug = (bool) $options['debug'];
  128.         $this->setCharset($options['charset'] ?? 'UTF-8');
  129.         $this->autoReload = null === $options['auto_reload'] ? $this->debug : (bool) $options['auto_reload'];
  130.         $this->strictVariables = (bool) $options['strict_variables'];
  131.         $this->setCache($options['cache']);
  132.         $this->extensionSet = new ExtensionSet();
  133.         $this->defaultRuntimeLoader = new FactoryRuntimeLoader([
  134.             EscaperRuntime::class => function () { return new EscaperRuntime($this->charset); },
  135.         ]);
  136.         $this->addExtension(new CoreExtension());
  137.         $escaperExt = new EscaperExtension($options['autoescape']);
  138.         $escaperExt->setEnvironment($this, false);
  139.         $this->addExtension($escaperExt);
  140.         if (\PHP_VERSION_ID >= 80000) {
  141.             $this->addExtension(new YieldNotReadyExtension($this->useYield));
  142.         }
  143.         $this->addExtension(new OptimizerExtension($this->optimizations));
  144.     }
  145.     public function __clone()
  146.     {
  147.         trigger_deprecation('twig/twig', '3.30', 'Cloning a "%s" instance is deprecated and will throw in Twig 4.0; build a new environment instead.', self::class);
  148.     }
  149.     /**
  150.      * @internal
  151.      */
  152.     public function useYield(): bool
  153.     {
  154.         return $this->useYield;
  155.     }
  156.     /**
  157.      * Enables debugging mode.
  158.      *
  159.      * @return void
  160.      */
  161.     public function enableDebug()
  162.     {
  163.         $this->debug = true;
  164.         $this->optionsHash = null;
  165.     }
  166.     /**
  167.      * Disables debugging mode.
  168.      *
  169.      * @return void
  170.      */
  171.     public function disableDebug()
  172.     {
  173.         $this->debug = false;
  174.         $this->optionsHash = null;
  175.     }
  176.     /**
  177.      * Checks if debug mode is enabled.
  178.      *
  179.      * @return bool true if debug mode is enabled, false otherwise
  180.      */
  181.     public function isDebug()
  182.     {
  183.         return $this->debug;
  184.     }
  185.     /**
  186.      * Enables the auto_reload option.
  187.      *
  188.      * @return void
  189.      */
  190.     public function enableAutoReload()
  191.     {
  192.         $this->autoReload = true;
  193.     }
  194.     /**
  195.      * Disables the auto_reload option.
  196.      *
  197.      * @return void
  198.      */
  199.     public function disableAutoReload()
  200.     {
  201.         $this->autoReload = false;
  202.     }
  203.     /**
  204.      * Checks if the auto_reload option is enabled.
  205.      *
  206.      * @return bool true if auto_reload is enabled, false otherwise
  207.      */
  208.     public function isAutoReload()
  209.     {
  210.         return $this->autoReload;
  211.     }
  212.     /**
  213.      * Enables the strict_variables option.
  214.      *
  215.      * @return void
  216.      */
  217.     public function enableStrictVariables()
  218.     {
  219.         $this->strictVariables = true;
  220.         $this->optionsHash = null;
  221.     }
  222.     /**
  223.      * Disables the strict_variables option.
  224.      *
  225.      * @return void
  226.      */
  227.     public function disableStrictVariables()
  228.     {
  229.         $this->strictVariables = false;
  230.         $this->optionsHash = null;
  231.     }
  232.     /**
  233.      * Checks if the strict_variables option is enabled.
  234.      *
  235.      * @return bool true if strict_variables is enabled, false otherwise
  236.      */
  237.     public function isStrictVariables()
  238.     {
  239.         return $this->strictVariables;
  240.     }
  241.     public function removeCache(string $name): void
  242.     {
  243.         $cls = $this->getTemplateClass($name);
  244.         $this->hotCache[$name] = $cls.'_'.bin2hex(random_bytes(16));
  245.         unset($this->loadedWrappers[$cls]);
  246.         if ($this->cache instanceof RemovableCacheInterface) {
  247.             $this->cache->remove($name, $cls);
  248.         } else {
  249.             throw new \LogicException(\sprintf('The "%s" cache class does not support removing template cache as it does not implement the "RemovableCacheInterface" interface.', \get_class($this->cache)));
  250.         }
  251.     }
  252.     /**
  253.      * Gets the current cache implementation.
  254.      *
  255.      * @param bool $original Whether to return the original cache option or the real cache instance
  256.      *
  257.      * @return CacheInterface|string|false A Twig\Cache\CacheInterface implementation,
  258.      *                                     an absolute path to the compiled templates,
  259.      *                                     or false to disable cache
  260.      */
  261.     public function getCache($original = true)
  262.     {
  263.         return $original ? $this->originalCache : $this->cache;
  264.     }
  265.     /**
  266.      * Sets the current cache implementation.
  267.      *
  268.      * @param CacheInterface|string|false $cache A Twig\Cache\CacheInterface implementation,
  269.      *                                           an absolute path to the compiled templates,
  270.      *                                           or false to disable cache
  271.      *
  272.      * @return void
  273.      */
  274.     public function setCache($cache)
  275.     {
  276.         if (\is_string($cache)) {
  277.             $this->originalCache = $cache;
  278.             $this->cache = new FilesystemCache($cache, $this->autoReload ? FilesystemCache::FORCE_BYTECODE_INVALIDATION : 0);
  279.         } elseif (false === $cache) {
  280.             $this->originalCache = $cache;
  281.             $this->cache = new NullCache();
  282.         } elseif ($cache instanceof CacheInterface) {
  283.             $this->originalCache = $this->cache = $cache;
  284.         } else {
  285.             throw new \LogicException('Cache can only be a string, false, or a \Twig\Cache\CacheInterface implementation.');
  286.         }
  287.     }
  288.     /**
  289.      * Gets the template class associated with the given string.
  290.      *
  291.      * The generated template class is based on the following parameters:
  292.      *
  293.      *  * The cache key for the given template;
  294.      *  * The currently enabled extensions;
  295.      *  * PHP version;
  296.      *  * Twig version;
  297.      *  * Options with what environment was created.
  298.      *
  299.      * @param string   $name  The name for which to calculate the template class name
  300.      * @param int|null $index The index if it is an embedded template
  301.      *
  302.      * @internal
  303.      */
  304.     public function getTemplateClass(string $name, ?int $index = null): string
  305.     {
  306.         $key = ($this->hotCache[$name] ?? $this->getLoader()->getCacheKey($name)).($this->optionsHash ??= $this->getOptionsHash());
  307.         if ($this->hasExtension(EscaperExtension::class)) {
  308.             $key .= ':autoescape:'.self::encodeAutoescapeStrategy($this->getExtension(EscaperExtension::class)->getDefaultStrategy($name));
  309.         }
  310.         if ($this->hasExtension(SandboxExtension::class)) {
  311.             $key .= ':sandbox:'.$this->extensionSet->getSandboxSignature();
  312.         }
  313.         return '__TwigTemplate_'.hash(\PHP_VERSION_ID < 80100 ? 'sha256' : 'xxh128', $key).(null === $index ? '' : '___'.$index);
  314.     }
  315.     /**
  316.      * Renders a template.
  317.      *
  318.      * @param string|TemplateWrapper $name The template name
  319.      *
  320.      * @throws LoaderError  When the template cannot be found
  321.      * @throws SyntaxError  When an error occurred during compilation
  322.      * @throws RuntimeError When an error occurred during rendering
  323.      */
  324.     public function render($name, array $context = []): string
  325.     {
  326.         return $this->load($name)->render($context);
  327.     }
  328.     /**
  329.      * Displays a template.
  330.      *
  331.      * @param string|TemplateWrapper $name The template name
  332.      *
  333.      * @throws LoaderError  When the template cannot be found
  334.      * @throws SyntaxError  When an error occurred during compilation
  335.      * @throws RuntimeError When an error occurred during rendering
  336.      */
  337.     public function display($name, array $context = []): void
  338.     {
  339.         $this->load($name)->display($context);
  340.     }
  341.     /**
  342.      * Loads a template.
  343.      *
  344.      * @param string|TemplateWrapper $name The template name
  345.      *
  346.      * @throws LoaderError  When the template cannot be found
  347.      * @throws RuntimeError When a previously generated cache is corrupted
  348.      * @throws SyntaxError  When an error occurred during compilation
  349.      */
  350.     public function load($name): TemplateWrapper
  351.     {
  352.         if ($name instanceof TemplateWrapper) {
  353.             $name->unwrap($this);
  354.             return $name;
  355.         }
  356.         if ($name instanceof Template) {
  357.             trigger_deprecation('twig/twig', '3.9', 'Passing a "%s" instance to "%s" is deprecated.', self::class, __METHOD__);
  358.             return $name;
  359.         }
  360.         $cls = $this->getTemplateClass($name);
  361.         return $this->loadedWrappers[$cls] ??= new TemplateWrapper($this, $this->loadTemplate($cls, $name));
  362.     }
  363.     /**
  364.      * Loads a template internal representation.
  365.      *
  366.      * This method is for internal use only and should never be called
  367.      * directly.
  368.      *
  369.      * @param string   $name  The template name
  370.      * @param int|null $index The index if it is an embedded template
  371.      *
  372.      * @throws LoaderError  When the template cannot be found
  373.      * @throws RuntimeError When a previously generated cache is corrupted
  374.      * @throws SyntaxError  When an error occurred during compilation
  375.      *
  376.      * @internal
  377.      */
  378.     public function loadTemplate(string $cls, string $name, ?int $index = null): Template
  379.     {
  380.         $mainCls = $cls;
  381.         if (null !== $index) {
  382.             $cls .= '___'.$index;
  383.         }
  384.         if (isset($this->loadedTemplates[$cls])) {
  385.             return $this->loadedTemplates[$cls];
  386.         }
  387.         if (!class_exists($cls, false)) {
  388.             $key = $this->cache->generateKey($name, $mainCls);
  389.             if (!$this->isAutoReload() || $this->isTemplateFresh($name, $this->cache->getTimestamp($key))) {
  390.                 $this->cache->load($key);
  391.             }
  392.             if (!class_exists($cls, false)) {
  393.                 $source = $this->getLoader()->getSourceContext($name);
  394.                 $content = $this->compileSource($source);
  395.                 if (!isset($this->hotCache[$name])) {
  396.                     $this->cache->write($key, $content);
  397.                     $this->cache->load($key);
  398.                 }
  399.                 if (!class_exists($mainCls, false)) {
  400.                     /* Last line of defense if either $this->bcWriteCacheFile was used,
  401.                      * $this->cache is implemented as a no-op or we have a race condition
  402.                      * where the cache was cleared between the above calls to write to and load from
  403.                      * the cache.
  404.                      */
  405.                     eval('?>'.$content);
  406.                 }
  407.                 if (!class_exists($cls, false)) {
  408.                     throw new RuntimeError(\sprintf('Failed to load Twig template "%s", index "%s": cache might be corrupted.', $name, $index), -1, $source);
  409.                 }
  410.             }
  411.         }
  412.         $this->extensionSet->initRuntime();
  413.         return $this->loadedTemplates[$cls] = new $cls($this);
  414.     }
  415.     /**
  416.      * Creates a template from source.
  417.      *
  418.      * This method should not be used as a generic way to load templates.
  419.      *
  420.      * @param string      $template The template source
  421.      * @param string|null $name     An optional name of the template to be used in error messages
  422.      *
  423.      * @throws LoaderError When the template cannot be found
  424.      * @throws SyntaxError When an error occurred during compilation
  425.      */
  426.     public function createTemplate(string $template, ?string $name = null): TemplateWrapper
  427.     {
  428.         $hash = hash(\PHP_VERSION_ID < 80100 ? 'sha256' : 'xxh128', $template, false);
  429.         if (null !== $name) {
  430.             $name = \sprintf('%s (string template %s)', $name, $hash);
  431.         } else {
  432.             $name = \sprintf('__string_template__%s', $hash);
  433.         }
  434.         $loader = new ChainLoader([
  435.             new ArrayLoader([$name => $template]),
  436.             $current = $this->getLoader(),
  437.         ]);
  438.         $this->setLoader($loader);
  439.         try {
  440.             return new TemplateWrapper($this, $this->loadTemplate($this->getTemplateClass($name), $name));
  441.         } finally {
  442.             $this->setLoader($current);
  443.         }
  444.     }
  445.     /**
  446.      * Returns true if the template is still fresh.
  447.      *
  448.      * Besides checking the loader for freshness information,
  449.      * this method also checks if the enabled extensions have
  450.      * not changed.
  451.      *
  452.      * @param int $time The last modification time of the cached template
  453.      */
  454.     public function isTemplateFresh(string $name, int $time): bool
  455.     {
  456.         return $this->extensionSet->getLastModified() <= $time && $this->getLoader()->isFresh($name, $time);
  457.     }
  458.     /**
  459.      * Tries to load a template consecutively from an array.
  460.      *
  461.      * Similar to load() but it also accepts instances of \Twig\TemplateWrapper
  462.      * and an array of templates where each is tried to be loaded.
  463.      *
  464.      * @param string|TemplateWrapper|array<string|TemplateWrapper> $names A template or an array of templates to try consecutively
  465.      *
  466.      * @throws LoaderError When none of the templates can be found
  467.      * @throws SyntaxError When an error occurred during compilation
  468.      */
  469.     public function resolveTemplate($names): TemplateWrapper
  470.     {
  471.         if (!\is_array($names)) {
  472.             return $this->load($names);
  473.         }
  474.         $count = \count($names);
  475.         foreach ($names as $name) {
  476.             if ($name instanceof Template) {
  477.                 trigger_deprecation('twig/twig', '3.9', 'Passing a "%s" instance to "%s" is deprecated.', Template::class, __METHOD__);
  478.                 if (!$name->isOwnedBy($this)) {
  479.                     throw new RuntimeError(\sprintf('A "%s" can only be used with the "%s" that created it.', Template::class, self::class));
  480.                 }
  481.                 return new TemplateWrapper($this, $name);
  482.             }
  483.             if ($name instanceof TemplateWrapper) {
  484.                 return $this->load($name);
  485.             }
  486.             if (1 !== $count && !$this->getLoader()->exists($name)) {
  487.                 continue;
  488.             }
  489.             return $this->load($name);
  490.         }
  491.         throw new LoaderError(\sprintf('Unable to find one of the following templates: "%s".', implode('", "', $names)));
  492.     }
  493.     /**
  494.      * @return void
  495.      */
  496.     public function setLexer(Lexer $lexer)
  497.     {
  498.         $this->lexer = $lexer;
  499.     }
  500.     /**
  501.      * @throws SyntaxError When the code is syntactically wrong
  502.      */
  503.     public function tokenize(Source $source): TokenStream
  504.     {
  505.         if (null === $this->lexer) {
  506.             $this->lexer = new Lexer($this);
  507.         }
  508.         return $this->lexer->tokenize($source);
  509.     }
  510.     /**
  511.      * @return void
  512.      */
  513.     public function setParser(Parser $parser)
  514.     {
  515.         $this->parser = $parser;
  516.     }
  517.     /**
  518.      * Converts a token stream to a node tree.
  519.      *
  520.      * @throws SyntaxError When the token stream is syntactically or semantically wrong
  521.      */
  522.     public function parse(TokenStream $stream): ModuleNode
  523.     {
  524.         if (null === $this->parser) {
  525.             $this->parser = new Parser($this);
  526.         }
  527.         return $this->parser->parse($stream);
  528.     }
  529.     /**
  530.      * @return void
  531.      */
  532.     public function setCompiler(Compiler $compiler)
  533.     {
  534.         $this->compiler = $compiler;
  535.     }
  536.     /**
  537.      * Compiles a node and returns the PHP code.
  538.      */
  539.     public function compile(Node $node): string
  540.     {
  541.         if (null === $this->compiler) {
  542.             $this->compiler = new Compiler($this);
  543.         }
  544.         return $this->compiler->compile($node)->getSource();
  545.     }
  546.     /**
  547.      * Compiles a template source code.
  548.      *
  549.      * @throws SyntaxError When there was an error during tokenizing, parsing or compiling
  550.      */
  551.     public function compileSource(Source $source): string
  552.     {
  553.         try {
  554.             return $this->compile($this->parse($this->tokenize($source)));
  555.         } catch (Error $e) {
  556.             $e->setSourceContext($source);
  557.             throw $e;
  558.         } catch (\Exception $e) {
  559.             throw new SyntaxError(\sprintf('An exception has been thrown during the compilation of a template ("%s").', $e->getMessage()), -1, $source, $e);
  560.         }
  561.     }
  562.     /**
  563.      * @return void
  564.      */
  565.     public function setLoader(LoaderInterface $loader)
  566.     {
  567.         $this->loader = $loader;
  568.     }
  569.     public function getLoader(): LoaderInterface
  570.     {
  571.         return $this->loader;
  572.     }
  573.     /**
  574.      * @return void
  575.      */
  576.     public function setCharset(string $charset)
  577.     {
  578.         if ('UTF8' === $charset = strtoupper($charset ?: '')) {
  579.             // iconv on Windows requires "UTF-8" instead of "UTF8"
  580.             $charset = 'UTF-8';
  581.         }
  582.         $this->charset = $charset;
  583.     }
  584.     public function getCharset(): string
  585.     {
  586.         return $this->charset;
  587.     }
  588.     public function hasExtension(string $class): bool
  589.     {
  590.         return $this->extensionSet->hasExtension($class);
  591.     }
  592.     /**
  593.      * @return void
  594.      */
  595.     public function addRuntimeLoader(RuntimeLoaderInterface $loader)
  596.     {
  597.         $this->runtimeLoaders[] = $loader;
  598.     }
  599.     /**
  600.      * @template TExtension of ExtensionInterface
  601.      *
  602.      * @param class-string<TExtension> $class
  603.      *
  604.      * @return TExtension
  605.      */
  606.     public function getExtension(string $class): ExtensionInterface
  607.     {
  608.         $extension = $this->extensionSet->getExtension($class);
  609.         if (AttributeExtension::class === $extension::class && is_a($extension->getClass(), ExtensionInterface::class, true)) {
  610.             return $this->getRuntime($extension->getClass());
  611.         }
  612.         return $extension;
  613.     }
  614.     /**
  615.      * Returns the runtime implementation of a Twig element (filter/function/tag/test).
  616.      *
  617.      * @template TRuntime of object
  618.      *
  619.      * @param class-string<TRuntime> $class A runtime class name
  620.      *
  621.      * @return TRuntime The runtime implementation
  622.      *
  623.      * @throws RuntimeError When the template cannot be found
  624.      */
  625.     public function getRuntime(string $class)
  626.     {
  627.         if (isset($this->runtimes[$class])) {
  628.             return $this->runtimes[$class];
  629.         }
  630.         foreach ($this->runtimeLoaders as $loader) {
  631.             if (null !== $runtime = $loader->load($class)) {
  632.                 return $this->runtimes[$class] = $runtime;
  633.             }
  634.         }
  635.         if (null !== $runtime = $this->defaultRuntimeLoader->load($class)) {
  636.             return $this->runtimes[$class] = $runtime;
  637.         }
  638.         if ($this->extensionSet->hasExtension($class) && ($extension = $this->extensionSet->getExtension($class)) instanceof $class) {
  639.             return $this->runtimes[$class] = $extension;
  640.         }
  641.         throw new RuntimeError(\sprintf('Unable to load the "%s" runtime.', $class));
  642.     }
  643.     /**
  644.      * @return void
  645.      */
  646.     public function addExtension(ExtensionInterface $extension)
  647.     {
  648.         $this->extensionSet->addExtension($extension);
  649.         $this->optionsHash = null;
  650.     }
  651.     /**
  652.      * @param ExtensionInterface[] $extensions An array of extensions
  653.      *
  654.      * @return void
  655.      */
  656.     public function setExtensions(array $extensions)
  657.     {
  658.         $this->extensionSet->setExtensions($extensions);
  659.         $this->optionsHash = null;
  660.     }
  661.     /**
  662.      * @return ExtensionInterface[] An array of extensions (keys are for internal usage only and should not be relied on)
  663.      */
  664.     public function getExtensions(): array
  665.     {
  666.         return $this->extensionSet->getExtensions();
  667.     }
  668.     /**
  669.      * @return void
  670.      */
  671.     public function addTokenParser(TokenParserInterface $parser)
  672.     {
  673.         $this->extensionSet->addTokenParser($parser);
  674.     }
  675.     /**
  676.      * @return TokenParserInterface[]
  677.      *
  678.      * @internal
  679.      */
  680.     public function getTokenParsers(): array
  681.     {
  682.         return $this->extensionSet->getTokenParsers();
  683.     }
  684.     /**
  685.      * @internal
  686.      */
  687.     public function getTokenParser(string $name): ?TokenParserInterface
  688.     {
  689.         return $this->extensionSet->getTokenParser($name);
  690.     }
  691.     /**
  692.      * @param callable(string): (TokenParserInterface|false) $callable
  693.      */
  694.     public function registerUndefinedTokenParserCallback(callable $callable): void
  695.     {
  696.         $this->extensionSet->registerUndefinedTokenParserCallback($callable);
  697.     }
  698.     /**
  699.      * @return void
  700.      */
  701.     public function addNodeVisitor(NodeVisitorInterface $visitor)
  702.     {
  703.         $this->extensionSet->addNodeVisitor($visitor);
  704.     }
  705.     /**
  706.      * @return NodeVisitorInterface[]
  707.      *
  708.      * @internal
  709.      */
  710.     public function getNodeVisitors(): array
  711.     {
  712.         return $this->extensionSet->getNodeVisitors();
  713.     }
  714.     /**
  715.      * @return void
  716.      */
  717.     public function addFilter(TwigFilter $filter)
  718.     {
  719.         $this->extensionSet->addFilter($filter);
  720.     }
  721.     /**
  722.      * @internal
  723.      */
  724.     public function getFilter(string $name): ?TwigFilter
  725.     {
  726.         return $this->extensionSet->getFilter($name);
  727.     }
  728.     /**
  729.      * @param callable(string): (TwigFilter|false) $callable
  730.      */
  731.     public function registerUndefinedFilterCallback(callable $callable): void
  732.     {
  733.         $this->extensionSet->registerUndefinedFilterCallback($callable);
  734.     }
  735.     /**
  736.      * Gets the registered Filters.
  737.      *
  738.      * Be warned that this method cannot return filters defined with registerUndefinedFilterCallback.
  739.      *
  740.      * @return TwigFilter[]
  741.      *
  742.      * @see registerUndefinedFilterCallback
  743.      *
  744.      * @internal
  745.      */
  746.     public function getFilters(): array
  747.     {
  748.         return $this->extensionSet->getFilters();
  749.     }
  750.     /**
  751.      * @return void
  752.      */
  753.     public function addTest(TwigTest $test)
  754.     {
  755.         $this->extensionSet->addTest($test);
  756.     }
  757.     /**
  758.      * @return TwigTest[]
  759.      *
  760.      * @internal
  761.      */
  762.     public function getTests(): array
  763.     {
  764.         return $this->extensionSet->getTests();
  765.     }
  766.     /**
  767.      * @internal
  768.      */
  769.     public function getTest(string $name): ?TwigTest
  770.     {
  771.         return $this->extensionSet->getTest($name);
  772.     }
  773.     /**
  774.      * @param callable(string): (TwigTest|false) $callable
  775.      */
  776.     public function registerUndefinedTestCallback(callable $callable): void
  777.     {
  778.         $this->extensionSet->registerUndefinedTestCallback($callable);
  779.     }
  780.     /**
  781.      * @return void
  782.      */
  783.     public function addFunction(TwigFunction $function)
  784.     {
  785.         $this->extensionSet->addFunction($function);
  786.     }
  787.     /**
  788.      * @internal
  789.      */
  790.     public function getFunction(string $name): ?TwigFunction
  791.     {
  792.         return $this->extensionSet->getFunction($name);
  793.     }
  794.     /**
  795.      * @param callable(string): (TwigFunction|false) $callable
  796.      */
  797.     public function registerUndefinedFunctionCallback(callable $callable): void
  798.     {
  799.         $this->extensionSet->registerUndefinedFunctionCallback($callable);
  800.     }
  801.     /**
  802.      * Gets registered functions.
  803.      *
  804.      * Be warned that this method cannot return functions defined with registerUndefinedFunctionCallback.
  805.      *
  806.      * @return TwigFunction[]
  807.      *
  808.      * @see registerUndefinedFunctionCallback
  809.      *
  810.      * @internal
  811.      */
  812.     public function getFunctions(): array
  813.     {
  814.         return $this->extensionSet->getFunctions();
  815.     }
  816.     /**
  817.      * Registers a Global.
  818.      *
  819.      * New globals can be added before compiling or rendering a template;
  820.      * but after, you can only update existing globals.
  821.      *
  822.      * @param mixed $value The global value
  823.      *
  824.      * @return void
  825.      */
  826.     public function addGlobal(string $name, $value)
  827.     {
  828.         if ($this->extensionSet->isInitialized() && !\array_key_exists($name, $this->getGlobals())) {
  829.             throw new \LogicException(\sprintf('Unable to add global "%s" as the runtime or the extensions have already been initialized.', $name));
  830.         }
  831.         if (null !== $this->resolvedGlobals) {
  832.             $this->resolvedGlobals[$name] = $value;
  833.         } else {
  834.             $this->globals[$name] = $value;
  835.         }
  836.     }
  837.     /**
  838.      * @return array<string, mixed>
  839.      */
  840.     public function getGlobals(): array
  841.     {
  842.         if ($this->extensionSet->isInitialized()) {
  843.             if (null === $this->resolvedGlobals) {
  844.                 $this->resolvedGlobals = array_merge($this->extensionSet->getGlobals(), $this->globals);
  845.             }
  846.             return $this->resolvedGlobals;
  847.         }
  848.         return array_merge($this->extensionSet->getGlobals(), $this->globals);
  849.     }
  850.     public function resetGlobals(): void
  851.     {
  852.         $this->resolvedGlobals = null;
  853.         $this->extensionSet->resetGlobals();
  854.     }
  855.     /**
  856.      * @deprecated since Twig 3.14
  857.      */
  858.     public function mergeGlobals(array $context): array
  859.     {
  860.         trigger_deprecation('twig/twig', '3.14', 'The "%s" method is deprecated.', __METHOD__);
  861.         return $context + $this->getGlobals();
  862.     }
  863.     /**
  864.      * @internal
  865.      */
  866.     public function getExpressionParsers(): ExpressionParsers
  867.     {
  868.         return $this->extensionSet->getExpressionParsers();
  869.     }
  870.     private static function encodeAutoescapeStrategy($strategy): string
  871.     {
  872.         if (false === $strategy) {
  873.             return 'false';
  874.         }
  875.         if (\is_string($strategy)) {
  876.             return 'string:'.\strlen($strategy).':'.$strategy;
  877.         }
  878.         return 'invalid:'.get_debug_type($strategy).':'.(int) (bool) $strategy;
  879.     }
  880.     private function getOptionsHash(): string
  881.     {
  882.         return implode(':', [
  883.             $this->extensionSet->getSignature(),
  884.             \PHP_MAJOR_VERSION,
  885.             \PHP_MINOR_VERSION,
  886.             self::VERSION,
  887.             (int) $this->debug,
  888.             (int) $this->strictVariables,
  889.             $this->useYield ? '1' : '0',
  890.             $this->optimizations,
  891.         ]);
  892.     }
  893. }