vendor/netgen/layouts-core/lib/View/Twig/ContextualizedTwigTemplate.php line 67

  1. <?php
  2. declare(strict_types=1);
  3. namespace Netgen\Layouts\View\Twig;
  4. use Throwable;
  5. use Twig\Template;
  6. use function ob_end_clean;
  7. use function ob_get_clean;
  8. use function ob_get_level;
  9. use function ob_start;
  10. /**
  11.  * Wrapper around a Twig template with a context included (all variables
  12.  * available inside the template).
  13.  */
  14. final class ContextualizedTwigTemplate
  15. {
  16.     private Template $template;
  17.     /**
  18.      * @var array<string, mixed>
  19.      */
  20.     private array $context;
  21.     /**
  22.      * @var array<string, mixed>
  23.      */
  24.     private array $blocks;
  25.     /**
  26.      * @param array<string, mixed> $context
  27.      * @param array<string, mixed> $blocks
  28.      */
  29.     public function __construct(Template $template, array $context = [], array $blocks = [])
  30.     {
  31.         $this->template $template;
  32.         $this->context $context;
  33.         $this->blocks $blocks;
  34.     }
  35.     /**
  36.      * Returns the context for this template.
  37.      *
  38.      * @return array<string, mixed>
  39.      */
  40.     public function getContext(): array
  41.     {
  42.         return $this->context;
  43.     }
  44.     /**
  45.      * Returns if the template has a block with provided name.
  46.      */
  47.     public function hasBlock(string $blockName): bool
  48.     {
  49.         return $this->template->hasBlock($blockName$this->context$this->blocks);
  50.     }
  51.     /**
  52.      * Renders the provided block. If block does not exist, an empty string will be returned.
  53.      *
  54.      * @throws \Throwable
  55.      */
  56.     public function renderBlock(string $blockName): string
  57.     {
  58.         if (!$this->template->hasBlock($blockName$this->context$this->blocks)) {
  59.             return '';
  60.         }
  61.         $level ob_get_level();
  62.         ob_start();
  63.         try {
  64.             $this->template->displayBlock($blockName$this->context$this->blocks);
  65.         } catch (Throwable $t) {
  66.             while (ob_get_level() > $level) {
  67.                 ob_end_clean();
  68.             }
  69.             throw $t;
  70.         }
  71.         return (string) ob_get_clean();
  72.     }
  73. }