vendor/twig/twig/src/Template.php line 510

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of Twig.
  4.  *
  5.  * (c) Fabien Potencier
  6.  * (c) Armin Ronacher
  7.  *
  8.  * For the full copyright and license information, please view the LICENSE
  9.  * file that was distributed with this source code.
  10.  */
  11. namespace Twig;
  12. use Twig\Error\Error;
  13. use Twig\Error\RuntimeError;
  14. use Twig\Loader\LoaderInterface;
  15. /**
  16.  * Default base class for compiled templates.
  17.  *
  18.  * This class is an implementation detail of how template compilation currently
  19.  * works, which might change. It should never be used directly. Use $twig->load()
  20.  * instead, which returns an instance of \Twig\TemplateWrapper.
  21.  *
  22.  * @author Fabien Potencier <[email protected]>
  23.  *
  24.  * @internal
  25.  */
  26. abstract class Template
  27. {
  28.     public const ANY_CALL = 'any';
  29.     public const ARRAY_CALL = 'array';
  30.     public const METHOD_CALL = 'method';
  31.     protected $parent;
  32.     protected $parents = [];
  33.     protected $blocks = [];
  34.     protected $traits = [];
  35.     protected $traitAliases = [];
  36.     protected $extensions = [];
  37.     protected $sandbox;
  38.     private $useYield;
  39.     private ?MacroNamespace $macroNamespace = null;
  40.     private ?LoaderInterface $loader = null;
  41.     private ?string $sourcePath = null;
  42.     public function __construct(
  43.         protected Environment $env,
  44.     ) {
  45.         $this->useYield = $env->useYield();
  46.         $this->extensions = $env->getExtensions();
  47.         $this->loader = $env->getLoader();
  48.     }
  49.     /**
  50.      * Returns the template name.
  51.      */
  52.     abstract public function getTemplateName(): string;
  53.     /**
  54.      * Returns debug information about the template.
  55.      *
  56.      * @return array<int, int> Debug information
  57.      */
  58.     abstract public function getDebugInfo(): array;
  59.     /**
  60.      * Returns information about the original template source code.
  61.      */
  62.     abstract public function getSourceContext(): Source;
  63.     /**
  64.      * Returns the path of the template source as resolved by the loader the template was instantiated with.
  65.      */
  66.     protected function getSourcePath(): string
  67.     {
  68.         try {
  69.             return $this->sourcePath ??= $this->loader?->getSourceContext($this->getTemplateName())->getPath() ?? '';
  70.         } catch (\Throwable) {
  71.             // the path is needed when an error is reported: a failing loader must not replace that error
  72.             return $this->sourcePath = '';
  73.         }
  74.     }
  75.     /**
  76.      * Returns the escaping strategy the template body was compiled with.
  77.      *
  78.      * This describes the template's own source, not its output: `autoescape`,
  79.      * `escape`, and anything rendered by a parent, embedded, or included
  80.      * template can use another strategy.
  81.      *
  82.      * @return string|false The strategy name or false when the template is not autoescaped
  83.      */
  84.     public function getDefaultEscapeStrategy(): string|false
  85.     {
  86.         return false;
  87.     }
  88.     /**
  89.      * Returns the parent template.
  90.      *
  91.      * This method is for internal use only and should never be called
  92.      * directly.
  93.      *
  94.      * @return self|false The parent template or false if there is no parent
  95.      */
  96.     public function getParent(array $context): self|false
  97.     {
  98.         if (null !== $this->parent) {
  99.             return $this->parent;
  100.         }
  101.         // The compiled doGetParent() may evaluate user expressions (filters,
  102.         // functions, method calls) when the parent name is dynamic. Make sure
  103.         // the sandbox security check runs first so those expressions cannot
  104.         // bypass the allow-list when getParent() is reached before the first
  105.         // ensureSecurityChecked() call on this template (e.g. via a macro call
  106.         // resolved against a parent, or yieldBlock() into a pre-warmed instance).
  107.         $this->ensureSecurityChecked();
  108.         try {
  109.             $parent = $this->doGetParent($context);
  110.         } catch (\Throwable $e) {
  111.             $this->handleException($e);
  112.         }
  113.         if (!$parent) {
  114.             return false;
  115.         }
  116.         if ($parent instanceof TemplateWrapper) {
  117.             $parent = $this->load($parent, -1);
  118.         }
  119.         if ($parent instanceof self) {
  120.             return $this->parents[$parent->getSourceContext()->getName()] = $parent;
  121.         }
  122.         if (!isset($this->parents[$parent])) {
  123.             $this->parents[$parent] = $this->load($parent, -1);
  124.         }
  125.         return $this->parents[$parent];
  126.     }
  127.     protected function doGetParent(array $context): bool|string|self|TemplateWrapper
  128.     {
  129.         return false;
  130.     }
  131.     public function isTraitable(): bool
  132.     {
  133.         return true;
  134.     }
  135.     /**
  136.      * Displays a parent block.
  137.      *
  138.      * This method is for internal use only and should never be called
  139.      * directly.
  140.      *
  141.      * @param string $name    The block name to display from the parent
  142.      * @param array  $context The context
  143.      * @param array  $blocks  The current set of blocks
  144.      */
  145.     public function displayParentBlock($name, array $context, array $blocks = []): void
  146.     {
  147.         foreach ($this->yieldParentBlock($name, $context, $blocks) as $data) {
  148.             echo $data;
  149.         }
  150.     }
  151.     /**
  152.      * Displays a block.
  153.      *
  154.      * This method is for internal use only and should never be called
  155.      * directly.
  156.      *
  157.      * @param string $name      The block name to display
  158.      * @param array  $context   The context
  159.      * @param array  $blocks    The current set of blocks
  160.      * @param bool   $useBlocks Whether to use the current set of blocks
  161.      */
  162.     public function displayBlock($name, array $context, array $blocks = [], $useBlocks = true, ?self $templateContext = null): void
  163.     {
  164.         foreach ($this->yieldBlock($name, $context, $blocks, $useBlocks, $templateContext) as $data) {
  165.             echo $data;
  166.         }
  167.     }
  168.     /**
  169.      * Renders a parent block.
  170.      *
  171.      * This method is for internal use only and should never be called
  172.      * directly.
  173.      *
  174.      * @param string $name    The block name to render from the parent
  175.      * @param array  $context The context
  176.      * @param array  $blocks  The current set of blocks
  177.      *
  178.      * @return string The rendered block
  179.      */
  180.     public function renderParentBlock($name, array $context, array $blocks = []): string
  181.     {
  182.         if (!$this->useYield) {
  183.             $level = ob_get_level();
  184.             if ($this->env->isDebug()) {
  185.                 ob_start();
  186.             } else {
  187.                 ob_start(static function () { return ''; });
  188.             }
  189.             try {
  190.                 $this->displayParentBlock($name, $context, $blocks);
  191.             } catch (\Throwable $e) {
  192.                 while (ob_get_level() > $level) {
  193.                     ob_end_clean();
  194.                 }
  195.                 throw $e;
  196.             }
  197.             return ob_get_clean();
  198.         }
  199.         $content = '';
  200.         foreach ($this->yieldParentBlock($name, $context, $blocks) as $data) {
  201.             $content .= $data;
  202.         }
  203.         return $content;
  204.     }
  205.     /**
  206.      * Renders a block.
  207.      *
  208.      * This method is for internal use only and should never be called
  209.      * directly.
  210.      *
  211.      * @param string $name      The block name to render
  212.      * @param array  $context   The context
  213.      * @param array  $blocks    The current set of blocks
  214.      * @param bool   $useBlocks Whether to use the current set of blocks
  215.      *
  216.      * @return string The rendered block
  217.      */
  218.     public function renderBlock($name, array $context, array $blocks = [], $useBlocks = true): string
  219.     {
  220.         if (!$this->useYield) {
  221.             $level = ob_get_level();
  222.             if ($this->env->isDebug()) {
  223.                 ob_start();
  224.             } else {
  225.                 ob_start(static function () { return ''; });
  226.             }
  227.             try {
  228.                 $this->displayBlock($name, $context, $blocks, $useBlocks);
  229.             } catch (\Throwable $e) {
  230.                 while (ob_get_level() > $level) {
  231.                     ob_end_clean();
  232.                 }
  233.                 throw $e;
  234.             }
  235.             return ob_get_clean();
  236.         }
  237.         $content = '';
  238.         foreach ($this->yieldBlock($name, $context, $blocks, $useBlocks) as $data) {
  239.             $content .= $data;
  240.         }
  241.         return $content;
  242.     }
  243.     /**
  244.      * Returns whether a block exists or not in the current context of the template.
  245.      *
  246.      * This method checks blocks defined in the current template
  247.      * or defined in "used" traits or defined in parent templates.
  248.      *
  249.      * @param string $name    The block name
  250.      * @param array  $context The context
  251.      * @param array  $blocks  The current set of blocks
  252.      *
  253.      * @return bool true if the block exists, false otherwise
  254.      */
  255.     public function hasBlock($name, array $context, array $blocks = []): bool
  256.     {
  257.         if (isset($blocks[$name])) {
  258.             return $blocks[$name][0] instanceof self;
  259.         }
  260.         if (isset($this->blocks[$name])) {
  261.             return true;
  262.         }
  263.         if ($parent = $this->getParent($context)) {
  264.             return $parent->hasBlock($name, $context);
  265.         }
  266.         return false;
  267.     }
  268.     /**
  269.      * Returns all block names in the current context of the template.
  270.      *
  271.      * This method checks blocks defined in the current template
  272.      * or defined in "used" traits or defined in parent templates.
  273.      *
  274.      * @param array $context The context
  275.      * @param array $blocks  The current set of blocks
  276.      *
  277.      * @return array<string> An array of block names
  278.      */
  279.     public function getBlockNames(array $context, array $blocks = []): array
  280.     {
  281.         $names = array_merge(array_keys($blocks), array_keys($this->blocks));
  282.         if ($parent = $this->getParent($context)) {
  283.             $names = array_merge($names, $parent->getBlockNames($context));
  284.         }
  285.         return array_unique($names);
  286.     }
  287.     /**
  288.      * @param string|TemplateWrapper|array<string|TemplateWrapper> $template
  289.      */
  290.     protected function load(string|TemplateWrapper|array $template, int $line, ?int $index = null): self
  291.     {
  292.         try {
  293.             if (\is_array($template)) {
  294.                 return $this->env->resolveTemplate($template)->unwrap($this->env);
  295.             }
  296.             if ($template instanceof TemplateWrapper) {
  297.                 return $template->unwrap($this->env);
  298.             }
  299.             if ($template === $this->getTemplateName()) {
  300.                 $class = static::class;
  301.                 if (false !== $pos = strrpos($class, '___', -1)) {
  302.                     $class = substr($class, 0, $pos);
  303.                 }
  304.             } else {
  305.                 $class = $this->env->getTemplateClass($template);
  306.             }
  307.             return $this->env->loadTemplate($class, $template, $index);
  308.         } catch (Error $e) {
  309.             if (!$e->getSourceContext()) {
  310.                 $e->setSourceContext($this->getSourceContext());
  311.             }
  312.             if ($e->getTemplateLine() > 0) {
  313.                 throw $e;
  314.             }
  315.             if (-1 === $line) {
  316.                 $e->guess();
  317.             } else {
  318.                 $e->setTemplateLine($line);
  319.             }
  320.             throw $e;
  321.         }
  322.     }
  323.     /**
  324.      * @param string|TemplateWrapper|array<string|TemplateWrapper> $template
  325.      *
  326.      * @deprecated since Twig 3.21 and will be removed in 4.0. Use Template::load() instead.
  327.      */
  328.     protected function loadTemplate($template, $templateName = null, ?int $line = null, ?int $index = null): self|TemplateWrapper
  329.     {
  330.         trigger_deprecation('twig/twig', '3.21', 'The "%s" method is deprecated.', __METHOD__);
  331.         if (null === $line) {
  332.             $line = -1;
  333.         }
  334.         if ($template instanceof self) {
  335.             return $template;
  336.         }
  337.         return $this->load($template, $line, $index);
  338.     }
  339.     /**
  340.      * @internal
  341.      *
  342.      * @return $this
  343.      */
  344.     public function unwrap(): self
  345.     {
  346.         return $this;
  347.     }
  348.     /**
  349.      * @internal
  350.      */
  351.     public function isOwnedBy(Environment $env): bool
  352.     {
  353.         return $this->env === $env;
  354.     }
  355.     /**
  356.      * Returns whether getParent() has stopped depending on the context, which
  357.      * only ever happens for a template with no parent or with a constant one.
  358.      */
  359.     public function hasFixedParent(): bool
  360.     {
  361.         return null !== $this->parent;
  362.     }
  363.     /**
  364.      * Returns all blocks.
  365.      *
  366.      * This method is for internal use only and should never be called
  367.      * directly.
  368.      *
  369.      * @return array An array of blocks
  370.      */
  371.     public function getBlocks(): array
  372.     {
  373.         return $this->blocks;
  374.     }
  375.     public function display(array $context, array $blocks = []): void
  376.     {
  377.         foreach ($this->yield($context, $blocks) as $data) {
  378.             echo $data;
  379.         }
  380.     }
  381.     public function render(array $context): string
  382.     {
  383.         if (!$this->useYield) {
  384.             $level = ob_get_level();
  385.             if ($this->env->isDebug()) {
  386.                 ob_start();
  387.             } else {
  388.                 ob_start(static function () { return ''; });
  389.             }
  390.             try {
  391.                 $this->display($context);
  392.             } catch (\Throwable $e) {
  393.                 while (ob_get_level() > $level) {
  394.                     ob_end_clean();
  395.                 }
  396.                 throw $e;
  397.             }
  398.             return ob_get_clean();
  399.         }
  400.         $content = '';
  401.         foreach ($this->yield($context) as $data) {
  402.             $content .= $data;
  403.         }
  404.         return $content;
  405.     }
  406.     /**
  407.      * @return iterable<scalar|\Stringable|null>
  408.      */
  409.     public function yield(array $context, array $blocks = []): iterable
  410.     {
  411.         $context += $this->env->getGlobals();
  412.         $blocks = array_merge($this->blocks, $blocks);
  413.         try {
  414.             $this->ensureSecurityChecked();
  415.             yield from $this->doDisplay($context, $blocks);
  416.         } catch (\Throwable $e) {
  417.             $this->handleException($e);
  418.         }
  419.     }
  420.     /**
  421.      * @return iterable<scalar|\Stringable|null>
  422.      */
  423.     public function yieldBlock($name, array $context, array $blocks = [], $useBlocks = true, ?self $templateContext = null): iterable
  424.     {
  425.         if ($useBlocks && isset($blocks[$name])) {
  426.             $template = $blocks[$name][0];
  427.             $block = $blocks[$name][1];
  428.         } elseif (isset($this->blocks[$name])) {
  429.             $template = $this->blocks[$name][0];
  430.             $block = $this->blocks[$name][1];
  431.             // expose this template's own blocks so nested block() calls resolve against them when the block is rendered directly (e.g. block(name, template))
  432.             $blocks = array_merge($this->blocks, $blocks);
  433.         } else {
  434.             $template = null;
  435.             $block = null;
  436.         }
  437.         // avoid RCEs when sandbox is enabled
  438.         if (null !== $template && !$template instanceof self) {
  439.             throw new \LogicException('A block must be a method on a \Twig\Template instance.');
  440.         }
  441.         if (null !== $template) {
  442.             try {
  443.                 $template->ensureSecurityChecked();
  444.                 yield from $template->$block($context, $blocks);
  445.             } catch (\Throwable $e) {
  446.                 $template->handleException($e);
  447.             }
  448.         } elseif ($parent = $this->getParent($context)) {
  449.             yield from $parent->unwrap()->yieldBlock($name, $context, array_merge($this->blocks, $blocks), false, $templateContext ?? $this);
  450.         } elseif (isset($blocks[$name])) {
  451.             throw new RuntimeError(\sprintf('Block "%s" should not call parent() in "%s" as the block does not exist in the parent template "%s".', $name, $blocks[$name][0]->getTemplateName(), $this->getTemplateName()), -1, $blocks[$name][0]->getSourceContext());
  452.         } else {
  453.             throw new RuntimeError(\sprintf('Block "%s" on template "%s" does not exist.', $name, $this->getTemplateName()), -1, ($templateContext ?? $this)->getSourceContext());
  454.         }
  455.     }
  456.     /**
  457.      * Yields a parent block.
  458.      *
  459.      * This method is for internal use only and should never be called
  460.      * directly.
  461.      *
  462.      * @param string $name    The block name to display from the parent
  463.      * @param array  $context The context
  464.      * @param array  $blocks  The current set of blocks
  465.      *
  466.      * @return iterable<scalar|\Stringable|null>
  467.      */
  468.     public function yieldParentBlock($name, array $context, array $blocks = []): iterable
  469.     {
  470.         if (isset($this->traits[$name])) {
  471.             yield from $this->traits[$name][0]->yieldBlock($this->traitAliases[$name] ?? $name, $context, $blocks, false);
  472.         } elseif ($parent = $this->getParent($context)) {
  473.             yield from $parent->unwrap()->yieldBlock($name, $context, $blocks, false);
  474.         } else {
  475.             throw new RuntimeError(\sprintf('The template has no parent and no traits defining the "%s" block.', $name), -1, $this->getSourceContext());
  476.         }
  477.     }
  478.     /**
  479.      * @internal
  480.      */
  481.     public function getMacroNamespace(): MacroNamespace
  482.     {
  483.         return $this->macroNamespace ??= new MacroNamespace($this, $this->loadDeclaredMacros());
  484.     }
  485.     /**
  486.      * @return array<string, TwigMacro>
  487.      */
  488.     protected function loadDeclaredMacros(): array
  489.     {
  490.         return [];
  491.     }
  492.     /**
  493.      * Runs the sandbox security check against the current sandbox state.
  494.      *
  495.      * @internal
  496.      */
  497.     public function ensureSecurityChecked(): void
  498.     {
  499.     }
  500.     /**
  501.      * Checks the "use" tag against the sandbox policy.
  502.      *
  503.      * The constructor resolves "use" traits eagerly, which reaches the loader,
  504.      * so that tag alone is checked here; the rest of the policy still runs at
  505.      * render time.
  506.      *
  507.      * @internal
  508.      */
  509.     public function ensureTraitsAllowed(): void
  510.     {
  511.         try {
  512.             $this->checkTraitsAllowed();
  513.         } catch (\Throwable $e) {
  514.             $this->handleException($e);
  515.         }
  516.     }
  517.     /**
  518.      * @internal
  519.      */
  520.     protected function checkTraitsAllowed(): void
  521.     {
  522.     }
  523.     /**
  524.      * @internal
  525.      */
  526.     protected function throwUninitializedMacroNamespace(int $line): never
  527.     {
  528.         throw new RuntimeError(\sprintf('Macros imported in the body of template "%s" are not available because the body was not rendered; move the "import" or "from" tag inside the block or the macro that uses it.', $this->getTemplateName()), $line, $this->getSourceContext());
  529.     }
  530.     /**
  531.      * Auto-generated method to display the template with the given context.
  532.      *
  533.      * @param array $context An array of parameters to pass to the template
  534.      * @param array $blocks  An array of blocks to pass to the template
  535.      *
  536.      * @return iterable<scalar|\Stringable|null>
  537.      */
  538.     abstract protected function doDisplay(array $context, array $blocks = []): iterable;
  539.     private function handleException(\Throwable $error): never
  540.     {
  541.         if ($error instanceof Error) {
  542.             if (!$error->getSourceContext()) {
  543.                 $error->setSourceContext($this->getSourceContext());
  544.             }
  545.             if (-1 === $error->getTemplateLine()) {
  546.                 $error->guess();
  547.             }
  548.             throw $error;
  549.         }
  550.         $error = new RuntimeError(\sprintf('An exception has been thrown during the rendering of a template ("%s").', $error->getMessage()), -1, $this->getSourceContext(), $error);
  551.         $error->guess();
  552.         throw $error;
  553.     }
  554. }