ci4

Форк
0
/
View.php 
525 строк · 14.9 Кб
1
<?php
2

3
declare(strict_types=1);
4

5
/**
6
 * This file is part of CodeIgniter 4 framework.
7
 *
8
 * (c) CodeIgniter Foundation <admin@codeigniter.com>
9
 *
10
 * For the full copyright and license information, please view
11
 * the LICENSE file that was distributed with this source code.
12
 */
13

14
namespace CodeIgniter\View;
15

16
use CodeIgniter\Autoloader\FileLocatorInterface;
17
use CodeIgniter\Debug\Toolbar\Collectors\Views;
18
use CodeIgniter\Filters\DebugToolbar;
19
use CodeIgniter\View\Exceptions\ViewException;
20
use Config\Toolbar;
21
use Config\View as ViewConfig;
22
use Psr\Log\LoggerInterface;
23
use RuntimeException;
24

25
/**
26
 * Class View
27
 *
28
 * @see \CodeIgniter\View\ViewTest
29
 */
30
class View implements RendererInterface
31
{
32
    use ViewDecoratorTrait;
33

34
    /**
35
     * Saved Data.
36
     *
37
     * @var array<string, mixed>
38
     */
39
    protected $data = [];
40

41
    /**
42
     * Data for the variables that are available in the Views.
43
     *
44
     * @var array<string, mixed>|null
45
     */
46
    protected $tempData;
47

48
    /**
49
     * The base directory to look in for our Views.
50
     *
51
     * @var string
52
     */
53
    protected $viewPath;
54

55
    /**
56
     * Data for rendering including Caching and Debug Toolbar data.
57
     *
58
     * @var array<string, mixed>
59
     */
60
    protected $renderVars = [];
61

62
    /**
63
     * Instance of FileLocator for when
64
     * we need to attempt to find a view
65
     * that's not in standard place.
66
     *
67
     * @var FileLocatorInterface
68
     */
69
    protected $loader;
70

71
    /**
72
     * Logger instance.
73
     *
74
     * @var LoggerInterface
75
     */
76
    protected $logger;
77

78
    /**
79
     * Should we store performance info?
80
     *
81
     * @var bool
82
     */
83
    protected $debug = false;
84

85
    /**
86
     * Cache stats about our performance here,
87
     * when CI_DEBUG = true
88
     *
89
     * @var list<array{start: float, end: float, view: string}>
90
     */
91
    protected $performanceData = [];
92

93
    /**
94
     * @var ViewConfig
95
     */
96
    protected $config;
97

98
    /**
99
     * Whether data should be saved between renders.
100
     *
101
     * @var bool
102
     */
103
    protected $saveData;
104

105
    /**
106
     * Number of loaded views
107
     *
108
     * @var int
109
     */
110
    protected $viewsCount = 0;
111

112
    /**
113
     * The name of the layout being used, if any.
114
     * Set by the `extend` method used within views.
115
     *
116
     * @var string|null
117
     */
118
    protected $layout;
119

120
    /**
121
     * Holds the sections and their data.
122
     *
123
     * @var array<string, list<string>>
124
     */
125
    protected $sections = [];
126

127
    /**
128
     * The name of the current section being rendered,
129
     * if any.
130
     *
131
     * @var string|null
132
     *
133
     * @deprecated
134
     */
135
    protected $currentSection;
136

137
    /**
138
     * The name of the current section being rendered,
139
     * if any.
140
     *
141
     * @var list<string>
142
     */
143
    protected $sectionStack = [];
144

145
    public function __construct(
146
        ViewConfig $config,
147
        ?string $viewPath = null,
148
        ?FileLocatorInterface $loader = null,
149
        ?bool $debug = null,
150
        ?LoggerInterface $logger = null
151
    ) {
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;
158
    }
159

160
    /**
161
     * Builds the output based upon a file name and any
162
     * data that has already been set.
163
     *
164
     * Valid $options:
165
     *  - cache      Number of seconds to cache for
166
     *  - cache_name Name to use for cache
167
     *
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.
175
     */
176
    public function render(string $view, ?array $options = null, ?bool $saveData = null): string
177
    {
178
        $this->renderVars['start'] = microtime(true);
179

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;
184

185
        $fileExt = pathinfo($view, PATHINFO_EXTENSION);
186
        // allow Views as .html, .tpl, etc (from CI3)
187
        $this->renderVars['view'] = ($fileExt === '') ? $view . '.php' : $view;
188

189
        $this->renderVars['options'] = $options ?? [];
190

191
        // Was it cached?
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);
196

197
            $this->renderVars['cacheName'] = $cacheName;
198

199
            if ($output = cache($this->renderVars['cacheName'])) {
200
                $this->logPerformance(
201
                    $this->renderVars['start'],
202
                    microtime(true),
203
                    $this->renderVars['view']
204
                );
205

206
                return $output;
207
            }
208
        }
209

210
        $this->renderVars['file'] = $this->viewPath . $this->renderVars['view'];
211

212
        if (! is_file($this->renderVars['file'])) {
213
            $this->renderVars['file'] = $this->loader->locateFile(
214
                $this->renderVars['view'],
215
                'Views',
216
                ($fileExt === '') ? 'php' : $fileExt
217
            );
218
        }
219

220
        // locateFile() will return false if the file cannot be found.
221
        if ($this->renderVars['file'] === false) {
222
            throw ViewException::forInvalidFile($this->renderVars['view']);
223
        }
224

225
        // Make our view data available to the view.
226
        $this->prepareTemplateData($saveData);
227

228
        // Save current vars
229
        $renderVars = $this->renderVars;
230

231
        $output = (function (): string {
232
            extract($this->tempData);
233
            ob_start();
234
            include $this->renderVars['file'];
235

236
            return ob_get_clean() ?: '';
237
        })();
238

239
        // Get back current vars
240
        $this->renderVars = $renderVars;
241

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;
248
            // Save current vars
249
            $renderVars = $this->renderVars;
250
            $output     = $this->render($layoutView, $options, $saveData);
251
            // Get back current vars
252
            $this->renderVars = $renderVars;
253
        }
254

255
        $output = $this->decorateOutput($output);
256

257
        $this->logPerformance(
258
            $this->renderVars['start'],
259
            microtime(true),
260
            $this->renderVars['view']
261
        );
262

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;
268
        } else {
269
            $afterFilters    = $filters->getFiltersClass()['after'];
270
            $debugBarEnabled = in_array(DebugToolbar::class, $afterFilters, true);
271
        }
272

273
        if (
274
            $this->debug && $debugBarEnabled
275
            && (! isset($options['debug']) || $options['debug'] === true)
276
        ) {
277
            $toolbarCollectors = config(Toolbar::class)->collectors;
278

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'];
283

284
                $output = '<!-- DEBUG-VIEW START ' . $this->renderVars['file'] . ' -->' . PHP_EOL
285
                    . $output . PHP_EOL
286
                    . '<!-- DEBUG-VIEW ENDED ' . $this->renderVars['file'] . ' -->' . PHP_EOL;
287
            }
288
        }
289

290
        // Should we cache?
291
        if (isset($this->renderVars['options']['cache'])) {
292
            cache()->save(
293
                $this->renderVars['cacheName'],
294
                $output,
295
                (int) $this->renderVars['options']['cache']
296
            );
297
        }
298

299
        $this->tempData = null;
300

301
        return $output;
302
    }
303

304
    /**
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".
308
     *
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.
316
     */
317
    public function renderString(string $view, ?array $options = null, ?bool $saveData = null): string
318
    {
319
        $start = microtime(true);
320
        $saveData ??= $this->saveData;
321
        $this->prepareTemplateData($saveData);
322

323
        $output = (function (string $view): string {
324
            extract($this->tempData);
325
            ob_start();
326
            eval('?>' . $view);
327

328
            return ob_get_clean() ?: '';
329
        })($view);
330

331
        $this->logPerformance($start, microtime(true), $this->excerpt($view));
332
        $this->tempData = null;
333

334
        return $output;
335
    }
336

337
    /**
338
     * Extract first bit of a long string and add ellipsis
339
     */
340
    public function excerpt(string $string, int $length = 20): string
341
    {
342
        return (strlen($string) > $length) ? substr($string, 0, $length - 3) . '...' : $string;
343
    }
344

345
    /**
346
     * Sets several pieces of view data at once.
347
     *
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
351
     */
352
    public function setData(array $data = [], ?string $context = null): RendererInterface
353
    {
354
        if ($context !== null) {
355
            $data = \esc($data, $context);
356
        }
357

358
        $this->tempData ??= $this->data;
359
        $this->tempData = array_merge($this->tempData, $data);
360

361
        return $this;
362
    }
363

364
    /**
365
     * Sets a single piece of view data.
366
     *
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
371
     */
372
    public function setVar(string $name, $value = null, ?string $context = null): RendererInterface
373
    {
374
        if ($context !== null) {
375
            $value = esc($value, $context);
376
        }
377

378
        $this->tempData ??= $this->data;
379
        $this->tempData[$name] = $value;
380

381
        return $this;
382
    }
383

384
    /**
385
     * Removes all of the view data from the system.
386
     */
387
    public function resetData(): RendererInterface
388
    {
389
        $this->data = [];
390

391
        return $this;
392
    }
393

394
    /**
395
     * Returns the current data that will be displayed in the view.
396
     *
397
     * @return array<string, mixed>
398
     */
399
    public function getData(): array
400
    {
401
        return $this->tempData ?? $this->data;
402
    }
403

404
    /**
405
     * Specifies that the current view should extend an existing layout.
406
     *
407
     * @return void
408
     */
409
    public function extend(string $layout)
410
    {
411
        $this->layout = $layout;
412
    }
413

414
    /**
415
     * Starts holds content for a section within the layout.
416
     *
417
     * @param string $name Section name
418
     *
419
     * @return void
420
     */
421
    public function section(string $name)
422
    {
423
        // Saved to prevent BC.
424
        $this->currentSection = $name;
425
        $this->sectionStack[] = $name;
426

427
        ob_start();
428
    }
429

430
    /**
431
     * Captures the last section
432
     *
433
     * @return void
434
     *
435
     * @throws RuntimeException
436
     */
437
    public function endSection()
438
    {
439
        $contents = ob_get_clean();
440

441
        if ($this->sectionStack === []) {
442
            throw new RuntimeException('View themes, no current section.');
443
        }
444

445
        $section = array_pop($this->sectionStack);
446

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] = [];
450
        }
451

452
        $this->sections[$section][] = $contents;
453
    }
454

455
    /**
456
     * Renders a section's contents.
457
     *
458
     * @param bool $saveData If true, saves data for subsequent calls,
459
     *                       if false, cleans the data after displaying.
460
     *
461
     * @return void
462
     */
463
    public function renderSection(string $sectionName, bool $saveData = false)
464
    {
465
        if (! isset($this->sections[$sectionName])) {
466
            echo '';
467

468
            return;
469
        }
470

471
        foreach ($this->sections[$sectionName] as $key => $contents) {
472
            echo $contents;
473
            if ($saveData === false) {
474
                unset($this->sections[$sectionName][$key]);
475
            }
476
        }
477
    }
478

479
    /**
480
     * Used within layout views to include additional views.
481
     *
482
     * @param array<string, mixed>|null $options
483
     * @param bool                      $saveData
484
     */
485
    public function include(string $view, ?array $options = null, $saveData = true): string
486
    {
487
        return $this->render($view, $options, $saveData);
488
    }
489

490
    /**
491
     * Returns the performance data that might have been collected
492
     * during the execution. Used primarily in the Debug Toolbar.
493
     *
494
     * @return list<array{start: float, end: float, view: string}>
495
     */
496
    public function getPerformanceData(): array
497
    {
498
        return $this->performanceData;
499
    }
500

501
    /**
502
     * Logs performance data for rendering a view.
503
     *
504
     * @return void
505
     */
506
    protected function logPerformance(float $start, float $end, string $view)
507
    {
508
        if ($this->debug) {
509
            $this->performanceData[] = [
510
                'start' => $start,
511
                'end'   => $end,
512
                'view'  => $view,
513
            ];
514
        }
515
    }
516

517
    protected function prepareTemplateData(bool $saveData): void
518
    {
519
        $this->tempData ??= $this->data;
520

521
        if ($saveData) {
522
            $this->data = $this->tempData;
523
        }
524
    }
525
}
526

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.