3
declare(strict_types=1);
6
* This file is part of CodeIgniter 4 framework.
8
* (c) CodeIgniter Foundation <admin@codeigniter.com>
10
* For the full copyright and license information, please view
11
* the LICENSE file that was distributed with this source code.
14
namespace CodeIgniter\View;
16
use CodeIgniter\Autoloader\FileLocatorInterface;
17
use CodeIgniter\Debug\Toolbar\Collectors\Views;
18
use CodeIgniter\Filters\DebugToolbar;
19
use CodeIgniter\View\Exceptions\ViewException;
21
use Config\View as ViewConfig;
22
use Psr\Log\LoggerInterface;
28
* @see \CodeIgniter\View\ViewTest
30
class View implements RendererInterface
32
use ViewDecoratorTrait;
37
* @var array<string, mixed>
42
* Data for the variables that are available in the Views.
44
* @var array<string, mixed>|null
49
* The base directory to look in for our Views.
56
* Data for rendering including Caching and Debug Toolbar data.
58
* @var array<string, mixed>
60
protected $renderVars = [];
63
* Instance of FileLocator for when
64
* we need to attempt to find a view
65
* that's not in standard place.
67
* @var FileLocatorInterface
74
* @var LoggerInterface
79
* Should we store performance info?
83
protected $debug = false;
86
* Cache stats about our performance here,
87
* when CI_DEBUG = true
89
* @var list<array{start: float, end: float, view: string}>
91
protected $performanceData = [];
99
* Whether data should be saved between renders.
106
* Number of loaded views
110
protected $viewsCount = 0;
113
* The name of the layout being used, if any.
114
* Set by the `extend` method used within views.
121
* Holds the sections and their data.
123
* @var array<string, list<string>>
125
protected $sections = [];
128
* The name of the current section being rendered,
135
protected $currentSection;
138
* The name of the current section being rendered,
143
protected $sectionStack = [];
145
public function __construct(
147
?string $viewPath = null,
148
?FileLocatorInterface $loader = null,
150
?LoggerInterface $logger = null
152
$this->config = $config;
153
$this->viewPath = rtrim($viewPath, '\\/ ') . DIRECTORY_SEPARATOR;
154
$this->loader = $loader ?? service('locator');
155
$this->logger = $logger ?? service('logger');
156
$this->debug = $debug ?? CI_DEBUG;
157
$this->saveData = (bool) $config->saveData;
161
* Builds the output based upon a file name and any
162
* data that has already been set.
165
* - cache Number of seconds to cache for
166
* - cache_name Name to use for cache
168
* @param string $view File name of the view source
169
* @param array<string, mixed>|null $options Reserved for 3rd-party uses since
170
* it might be needed to pass additional info
171
* to other template engines.
172
* @param bool|null $saveData If true, saves data for subsequent calls,
173
* if false, cleans the data after displaying,
174
* if null, uses the config setting.
176
public function render(string $view, ?array $options = null, ?bool $saveData = null): string
178
$this->renderVars['start'] = microtime(true);
180
// Store the results here so even if
181
// multiple views are called in a view, it won't
182
// clean it unless we mean it to.
183
$saveData ??= $this->saveData;
185
$fileExt = pathinfo($view, PATHINFO_EXTENSION);
186
// allow Views as .html, .tpl, etc (from CI3)
187
$this->renderVars['view'] = ($fileExt === '') ? $view . '.php' : $view;
189
$this->renderVars['options'] = $options ?? [];
192
if (isset($this->renderVars['options']['cache'])) {
193
$cacheName = $this->renderVars['options']['cache_name']
194
?? str_replace('.php', '', $this->renderVars['view']);
195
$cacheName = str_replace(['\\', '/'], '', $cacheName);
197
$this->renderVars['cacheName'] = $cacheName;
199
if ($output = cache($this->renderVars['cacheName'])) {
200
$this->logPerformance(
201
$this->renderVars['start'],
203
$this->renderVars['view']
210
$this->renderVars['file'] = $this->viewPath . $this->renderVars['view'];
212
if (! is_file($this->renderVars['file'])) {
213
$this->renderVars['file'] = $this->loader->locateFile(
214
$this->renderVars['view'],
216
($fileExt === '') ? 'php' : $fileExt
220
// locateFile() will return false if the file cannot be found.
221
if ($this->renderVars['file'] === false) {
222
throw ViewException::forInvalidFile($this->renderVars['view']);
225
// Make our view data available to the view.
226
$this->prepareTemplateData($saveData);
229
$renderVars = $this->renderVars;
231
$output = (function (): string {
232
extract($this->tempData);
234
include $this->renderVars['file'];
236
return ob_get_clean() ?: '';
239
// Get back current vars
240
$this->renderVars = $renderVars;
242
// When using layouts, the data has already been stored
243
// in $this->sections, and no other valid output
244
// is allowed in $output so we'll overwrite it.
245
if ($this->layout !== null && $this->sectionStack === []) {
246
$layoutView = $this->layout;
247
$this->layout = null;
249
$renderVars = $this->renderVars;
250
$output = $this->render($layoutView, $options, $saveData);
251
// Get back current vars
252
$this->renderVars = $renderVars;
255
$output = $this->decorateOutput($output);
257
$this->logPerformance(
258
$this->renderVars['start'],
260
$this->renderVars['view']
263
// Check if DebugToolbar is enabled.
264
$filters = service('filters');
265
$requiredAfterFilters = $filters->getRequiredFilters('after')[0];
266
if (in_array('toolbar', $requiredAfterFilters, true)) {
267
$debugBarEnabled = true;
269
$afterFilters = $filters->getFiltersClass()['after'];
270
$debugBarEnabled = in_array(DebugToolbar::class, $afterFilters, true);
274
$this->debug && $debugBarEnabled
275
&& (! isset($options['debug']) || $options['debug'] === true)
277
$toolbarCollectors = config(Toolbar::class)->collectors;
279
if (in_array(Views::class, $toolbarCollectors, true)) {
280
// Clean up our path names to make them a little cleaner
281
$this->renderVars['file'] = clean_path($this->renderVars['file']);
282
$this->renderVars['file'] = ++$this->viewsCount . ' ' . $this->renderVars['file'];
284
$output = '<!-- DEBUG-VIEW START ' . $this->renderVars['file'] . ' -->' . PHP_EOL
286
. '<!-- DEBUG-VIEW ENDED ' . $this->renderVars['file'] . ' -->' . PHP_EOL;
291
if (isset($this->renderVars['options']['cache'])) {
293
$this->renderVars['cacheName'],
295
(int) $this->renderVars['options']['cache']
299
$this->tempData = null;
305
* Builds the output based upon a string and any
306
* data that has already been set.
307
* Cache does not apply, because there is no "key".
309
* @param string $view The view contents
310
* @param array<string, mixed>|null $options Reserved for 3rd-party uses since
311
* it might be needed to pass additional info
312
* to other template engines.
313
* @param bool|null $saveData If true, saves data for subsequent calls,
314
* if false, cleans the data after displaying,
315
* if null, uses the config setting.
317
public function renderString(string $view, ?array $options = null, ?bool $saveData = null): string
319
$start = microtime(true);
320
$saveData ??= $this->saveData;
321
$this->prepareTemplateData($saveData);
323
$output = (function (string $view): string {
324
extract($this->tempData);
328
return ob_get_clean() ?: '';
331
$this->logPerformance($start, microtime(true), $this->excerpt($view));
332
$this->tempData = null;
338
* Extract first bit of a long string and add ellipsis
340
public function excerpt(string $string, int $length = 20): string
342
return (strlen($string) > $length) ? substr($string, 0, $length - 3) . '...' : $string;
346
* Sets several pieces of view data at once.
348
* @param non-empty-string|null $context The context to escape it for.
349
* If 'raw', no escaping will happen.
350
* @phpstan-param null|'html'|'js'|'css'|'url'|'attr'|'raw' $context
352
public function setData(array $data = [], ?string $context = null): RendererInterface
354
if ($context !== null) {
355
$data = \esc($data, $context);
358
$this->tempData ??= $this->data;
359
$this->tempData = array_merge($this->tempData, $data);
365
* Sets a single piece of view data.
367
* @param mixed $value
368
* @param non-empty-string|null $context The context to escape it for.
369
* If 'raw', no escaping will happen.
370
* @phpstan-param null|'html'|'js'|'css'|'url'|'attr'|'raw' $context
372
public function setVar(string $name, $value = null, ?string $context = null): RendererInterface
374
if ($context !== null) {
375
$value = esc($value, $context);
378
$this->tempData ??= $this->data;
379
$this->tempData[$name] = $value;
385
* Removes all of the view data from the system.
387
public function resetData(): RendererInterface
395
* Returns the current data that will be displayed in the view.
397
* @return array<string, mixed>
399
public function getData(): array
401
return $this->tempData ?? $this->data;
405
* Specifies that the current view should extend an existing layout.
409
public function extend(string $layout)
411
$this->layout = $layout;
415
* Starts holds content for a section within the layout.
417
* @param string $name Section name
421
public function section(string $name)
423
// Saved to prevent BC.
424
$this->currentSection = $name;
425
$this->sectionStack[] = $name;
431
* Captures the last section
435
* @throws RuntimeException
437
public function endSection()
439
$contents = ob_get_clean();
441
if ($this->sectionStack === []) {
442
throw new RuntimeException('View themes, no current section.');
445
$section = array_pop($this->sectionStack);
447
// Ensure an array exists so we can store multiple entries for this.
448
if (! array_key_exists($section, $this->sections)) {
449
$this->sections[$section] = [];
452
$this->sections[$section][] = $contents;
456
* Renders a section's contents.
458
* @param bool $saveData If true, saves data for subsequent calls,
459
* if false, cleans the data after displaying.
463
public function renderSection(string $sectionName, bool $saveData = false)
465
if (! isset($this->sections[$sectionName])) {
471
foreach ($this->sections[$sectionName] as $key => $contents) {
473
if ($saveData === false) {
474
unset($this->sections[$sectionName][$key]);
480
* Used within layout views to include additional views.
482
* @param array<string, mixed>|null $options
483
* @param bool $saveData
485
public function include(string $view, ?array $options = null, $saveData = true): string
487
return $this->render($view, $options, $saveData);
491
* Returns the performance data that might have been collected
492
* during the execution. Used primarily in the Debug Toolbar.
494
* @return list<array{start: float, end: float, view: string}>
496
public function getPerformanceData(): array
498
return $this->performanceData;
502
* Logs performance data for rendering a view.
506
protected function logPerformance(float $start, float $end, string $view)
509
$this->performanceData[] = [
517
protected function prepareTemplateData(bool $saveData): void
519
$this->tempData ??= $this->data;
522
$this->data = $this->tempData;