blob: c9c6b07c6693ce7ea9b89cda3f6cc946242e39c1 [file] [log] [blame]
Matthias Andreas Benkard12a57352021-12-28 18:02:04 +01001<?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
14/**
15 * Exposes a template to userland.
16 *
17 * @author Fabien Potencier <fabien@symfony.com>
18 */
19final class TemplateWrapper
20{
21 private $env;
22 private $template;
23
24 /**
25 * This method is for internal use only and should never be called
26 * directly (use Twig\Environment::load() instead).
27 *
28 * @internal
29 */
30 public function __construct(Environment $env, Template $template)
31 {
32 $this->env = $env;
33 $this->template = $template;
34 }
35
36 public function render(array $context = []): string
37 {
38 // using func_get_args() allows to not expose the blocks argument
39 // as it should only be used by internal code
40 return $this->template->render($context, \func_get_args()[1] ?? []);
41 }
42
43 public function display(array $context = [])
44 {
45 // using func_get_args() allows to not expose the blocks argument
46 // as it should only be used by internal code
47 $this->template->display($context, \func_get_args()[1] ?? []);
48 }
49
50 public function hasBlock(string $name, array $context = []): bool
51 {
52 return $this->template->hasBlock($name, $context);
53 }
54
55 /**
56 * @return string[] An array of defined template block names
57 */
58 public function getBlockNames(array $context = []): array
59 {
60 return $this->template->getBlockNames($context);
61 }
62
63 public function renderBlock(string $name, array $context = []): string
64 {
65 $context = $this->env->mergeGlobals($context);
66 $level = ob_get_level();
67 if ($this->env->isDebug()) {
68 ob_start();
69 } else {
70 ob_start(function () { return ''; });
71 }
72 try {
73 $this->template->displayBlock($name, $context);
74 } catch (\Throwable $e) {
75 while (ob_get_level() > $level) {
76 ob_end_clean();
77 }
78
79 throw $e;
80 }
81
82 return ob_get_clean();
83 }
84
85 public function displayBlock(string $name, array $context = [])
86 {
87 $this->template->displayBlock($name, $this->env->mergeGlobals($context));
88 }
89
90 public function getSourceContext(): Source
91 {
92 return $this->template->getSourceContext();
93 }
94
95 public function getTemplateName(): string
96 {
97 return $this->template->getTemplateName();
98 }
99
100 /**
101 * @internal
102 *
103 * @return Template
104 */
105 public function unwrap()
106 {
107 return $this->template;
108 }
109}