Passed
Pull Request — master (#97)
by Alexander
02:39
created

View::beginPage()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 10
cc 2
nc 2
nop 0
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\View;
6
7
use Psr\EventDispatcher\EventDispatcherInterface;
8
use Psr\Log\LoggerInterface;
9
use Yiisoft\I18n\Locale;
10
use Yiisoft\View\Event\AfterRender;
11
use Yiisoft\View\Event\BeforeRender;
12
use Yiisoft\View\Event\PageBegin;
13
use Yiisoft\View\Event\PageEnd;
14
use Yiisoft\View\Exception\ViewNotFoundException;
15
16
/**
17
 * View represents a view object in the MVC pattern.
18
 *
19
 * View provides a set of methods (e.g. {@see View::render()}) for rendering purpose.
20
 *
21
 * For more details and usage information on View, see the [guide article on views](guide:structure-views).
22
 */
23
class View implements DynamicContentAwareInterface
24
{
25
    /**
26
     * @var string view path
27
     */
28
    private string $basePath;
29
30
    /**
31
     * @var array a list of named output blocks. The keys are the block names and the values are the corresponding block
32
     * content. You can call {@see beginBlock()} and {@see endBlock()} to capture small fragments of a view.
33
     * They can be later accessed somewhere else through this property.
34
     */
35
    private array $blocks;
36
37
    /**
38
     * @var ViewContextInterface|null the context under which the {@see renderFile()} method is being invoked.
39
     */
40
    private ?ViewContextInterface $context = null;
41
42
    /**
43
     * @var string the default view file extension. This will be appended to view file names if they don't have file
44
     * extensions.
45
     */
46
    private string $defaultExtension = 'php';
47
48
    /**
49
     * @var array custom parameters that are shared among view templates.
50
     */
51
    private array $defaultParameters = [];
52
53
    /**
54
     * @var EventDispatcherInterface
55
     */
56
    protected EventDispatcherInterface $eventDispatcher;
57
58
    /**
59
     * @var array a list of available renderers indexed by their corresponding supported file extensions. Each renderer
60
     * may be a view renderer object or the configuration for creating the renderer object. For example, the
61
     * following configuration enables the Twig view renderer:
62
     *
63
     * ```php
64
     * [
65
     *     'twig' => ['class' => \Yiisoft\Yii\Twig\ViewRenderer::class],
66
     * ]
67
     * ```
68
     *
69
     * If no renderer is available for the given view file, the view file will be treated as a normal PHP and rendered
70
     * via PhpTemplateRenderer.
71
     */
72
    protected array $renderers = [];
73
74
    /**
75
     * @var Theme|null The theme object.
76
     */
77
    protected ?Theme $theme = null;
78
79
    /**
80
     * @var DynamicContentAwareInterface[] a list of currently active dynamic content class instances.
81
     */
82
    private array $cacheStack = [];
83
84
    /**
85
     * @var array a list of placeholders for embedding dynamic contents.
86
     */
87
    private array $dynamicPlaceholders = [];
88
89
    /**
90
     * @var string
91
     */
92
    private string $language = 'en';
93
94
    /**
95
     * @var LoggerInterface
96
     */
97
    private LoggerInterface $logger;
98
99
    /**
100
     * @var string
101
     */
102
    private string $sourceLanguage = 'en';
103
104
    /**
105
     * @var Locale|null source locale used to find localized view file.
106
     */
107
    private ?Locale $sourceLocale = null;
108
109
    private string $placeholderSignature;
110
111
    /**
112
     * @var array the view files currently being rendered. There may be multiple view files being
113
     * rendered at a moment because one view may be rendered within another.
114
     */
115
    private array $viewFiles = [];
116
117 21
    public function __construct(string $basePath, EventDispatcherInterface $eventDispatcher, LoggerInterface $logger)
118
    {
119 21
        $this->basePath = $basePath;
120 21
        $this->eventDispatcher = $eventDispatcher;
121 21
        $this->logger = $logger;
122 21
        $this->setPlaceholderSalt(__DIR__);
123 21
    }
124
125
    /**
126
     * @return static
127
     */
128 1
    public function withTheme(Theme $theme): self
129
    {
130 1
        $new = clone $this;
131 1
        $new->theme = $theme;
132 1
        return $new;
133
    }
134
135 21
    public function setPlaceholderSalt(string $salt): void
136
    {
137 21
        $this->placeholderSignature = dechex(crc32($salt));
138 21
    }
139
140 8
    public function getPlaceholderSignature(): string
141
    {
142 8
        return $this->placeholderSignature;
143
    }
144
145
    public function getBasePath(): string
146
    {
147
        return $this->basePath;
148
    }
149
150
    public function setRenderers(array $renderers): void
151
    {
152
        $this->renderers = $renderers;
153
    }
154
155
    public function setSourceLanguage(string $language): void
156
    {
157
        $this->sourceLanguage = $language;
158
    }
159
160
    public function setLanguage(string $language): void
161
    {
162
        $this->language = $language;
163
    }
164
165
    public function setContext(ViewContextInterface $context): void
166
    {
167
        $this->context = $context;
168
    }
169
170
    public function getDefaultExtension(): string
171
    {
172
        return $this->defaultExtension;
173
    }
174
175
    public function setDefaultExtension(string $defaultExtension): void
176
    {
177
        $this->defaultExtension = $defaultExtension;
178
    }
179
180
    public function getDefaultParameters(): array
181
    {
182
        return $this->defaultParameters;
183
    }
184
185 2
    public function setDefaultParameters(array $defaultParameters): void
186
    {
187 2
        $this->defaultParameters = $defaultParameters;
188 2
    }
189
190
    /**
191
     * {@see blocks}
192
     *
193
     * @param string $id
194
     * @param string $value
195
     */
196
    public function setBlock(string $id, string $value): void
197
    {
198
        $this->blocks[$id] = $value;
199
    }
200
201
    /**
202
     * {@see blocks}
203
     *
204
     * @param string $id
205
     */
206
    public function removeBlock(string $id): void
207
    {
208
        unset($this->blocks[$id]);
209
    }
210
211
    /**
212
     * {@see blocks}
213
     *
214
     * @param string $id
215
     *
216
     * @return string
217
     */
218
    public function getBlock(string $id): string
219
    {
220
        if (isset($this->blocks[$id])) {
221
            return $this->blocks[$id];
222
        }
223
224
        throw new \InvalidArgumentException('Block: "' . $id . '" not found.');
225
    }
226
227
    /**
228
     * {@see blocks}
229
     *
230
     * @param string $id
231
     *
232
     * @return bool
233
     */
234
    public function hasBlock(string $id): bool
235
    {
236
        return isset($this->blocks[$id]);
237
    }
238
239
    /**
240
     * Renders a view.
241
     *
242
     * The view to be rendered can be specified in one of the following formats:
243
     *
244
     * - [path alias](guide:concept-aliases) (e.g. "@app/views/site/index");
245
     * - absolute path within application (e.g. "//site/index"): the view name starts with double slashes. The actual
246
     *   view file will be looked for under the [[Application::viewPath|view path]] of the application.
247
     * - absolute path within current module (e.g. "/site/index"): the view name starts with a single slash. The actual
248
     *   view file will be looked for under the [[Module::viewPath|view path]] of the [[Controller::module|current module]].
249
     * - relative view (e.g. "index"): the view name does not start with `@` or `/`. The corresponding view file will be
250
     *   looked for under the {@see ViewContextInterface::getViewPath()} of the view `$context`.
251
     *   If `$context` is not given, it will be looked for under the directory containing the view currently
252
     *   being rendered (i.e., this happens when rendering a view within another view).
253
     *
254
     * @param string $view the view name.
255
     * @param array $parameters the parameters (name-value pairs) that will be extracted and made available in the view
256
     * file.
257
     * @param ViewContextInterface|null $context the context to be assigned to the view and can later be accessed via
258
     * {@see context} in the view. If the context implements {@see ViewContextInterface}, it may also be used to locate
259
     * the view file corresponding to a relative view name.
260
     *
261
     * @throws \RuntimeException if the view cannot be resolved.
262
     * @throws ViewNotFoundException if the view file does not exist.
263
     * @throws \Throwable
264
     *
265
     * {@see renderFile()}
266
     *
267
     * @return string the rendering result
268
     */
269 4
    public function render(string $view, array $parameters = [], ?ViewContextInterface $context = null): string
270
    {
271 4
        $viewFile = $this->findTemplateFile($view, $context);
272
273 4
        return $this->renderFile($viewFile, $parameters, $context);
274
    }
275
276
    /**
277
     * Finds the view file based on the given view name.
278
     *
279
     * @param string $view the view name or the [path alias](guide:concept-aliases) of the view file. Please refer to
280
     * {@see render()} on how to specify this parameter.
281
     * @param ViewContextInterface|null $context the context to be assigned to the view and can later be accessed via
282
     * {@see context} in the view. If the context implements {@see ViewContextInterface}, it may also be used to locate the
283
     * view file corresponding to a relative view name.
284
     *
285
     * @throws \RuntimeException if a relative view name is given while there is no active context to determine the
286
     * corresponding view file.
287
     *
288
     * @return string the view file path. Note that the file may not exist.
289
     */
290 4
    protected function findTemplateFile(string $view, ?ViewContextInterface $context = null): string
291
    {
292 4
        if (strncmp($view, '//', 2) === 0) {
293
            // path relative to basePath e.g. "//layouts/main"
294 4
            $file = $this->basePath . '/' . ltrim($view, '/');
295 1
        } elseif ($context instanceof ViewContextInterface) {
296
            // path provided by context
297
            $file = $context->getViewPath() . '/' . $view;
298 1
        } elseif (($currentViewFile = $this->getRequestedViewFile()) !== false) {
299
            // path relative to currently rendered view
300 1
            $file = dirname($currentViewFile) . '/' . $view;
0 ignored issues
show
Bug introduced by
It seems like $currentViewFile can also be of type true; however, parameter $path of dirname() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

300
            $file = dirname(/** @scrutinizer ignore-type */ $currentViewFile) . '/' . $view;
Loading history...
301
        } else {
302
            throw new \RuntimeException("Unable to resolve view file for view '$view': no active view context.");
303
        }
304
305 4
        if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
306 1
            return $file;
307
        }
308
309 3
        $path = $file . '.' . $this->defaultExtension;
310
311 3
        if ($this->defaultExtension !== 'php' && !is_file($path)) {
312
            $path = $file . '.php';
313
        }
314
315 3
        return $path;
316
    }
317
318
    /**
319
     * Renders a view file.
320
     *
321
     * If {@see theme} is enabled (not null), it will try to render the themed version of the view file as long as it
322
     * is available.
323
     *
324
     * If {@see renderers} is enabled (not null), the method will use it to render the view file. Otherwise,
325
     * it will simply include the view file as a normal PHP file, capture its output and
326
     * return it as a string.
327
     *
328
     * @param string $viewFile the view file. This can be either an absolute file path or an alias of it.
329
     * @param array $parameters the parameters (name-value pairs) that will be extracted and made available in the view
330
     * file.
331
     * @param ViewContextInterface|null $context the context that the view should use for rendering the view. If null,
332
     * existing {@see context} will be used.
333
     *
334
     * @throws \Throwable
335
     * @throws ViewNotFoundException if the view file does not exist
336
     *
337
     * @return string the rendering result
338
     */
339 11
    public function renderFile(string $viewFile, array $parameters = [], ?ViewContextInterface $context = null): string
340
    {
341 11
        $parameters = array_merge($this->defaultParameters, $parameters);
342
343
        // TODO: these two match now
344 11
        $requestedFile = $viewFile;
345
346 11
        if ($this->theme !== null) {
347 1
            $viewFile = $this->theme->applyTo($viewFile);
348
        }
349
350 11
        if (!is_file($viewFile)) {
351
            throw new ViewNotFoundException("The view file does not exist: $viewFile");
352
        }
353 11
        $viewFile = $this->localize($viewFile, $parameters['language'] ?? null, $parameters['sourceLanguage'] ?? null);
354
355 11
        $oldContext = $this->context;
356 11
        if ($context !== null) {
357
            $this->context = $context;
358
        }
359 11
        $output = '';
360 11
        $this->viewFiles[] = [
361 11
            'resolved' => $viewFile,
362 11
            'requested' => $requestedFile,
363
        ];
364
365 11
        if ($this->beforeRender($viewFile, $parameters)) {
366 11
            $this->logger->debug("Rendering view file: $viewFile");
367 11
            $ext = pathinfo($viewFile, PATHINFO_EXTENSION);
368 11
            $renderer = $this->renderers[$ext] ?? new PhpTemplateRenderer();
369
370 11
            $language = $this->language;
371 11
            $sourceLanguage = $this->sourceLanguage;
372 11
            $this->language = $parameters['language'] ?? $this->language;
373 11
            $this->sourceLanguage = $parameters['sourceLanguage'] ?? $this->sourceLanguage;
374
375 11
            $output = $renderer->render($this, $viewFile, $parameters);
376
377 11
            $this->language = $language;
378 11
            $this->sourceLanguage = $sourceLanguage;
379
380 11
            $output = $this->afterRender($viewFile, $parameters, $output);
381
        }
382
383 11
        array_pop($this->viewFiles);
384 11
        $this->context = $oldContext;
385
386 11
        return $output;
387
    }
388
389
    /**
390
     * Returns the localized version of a specified file.
391
     *
392
     * The searching is based on the specified language code. In particular, a file with the same name will be looked
393
     * for under the subdirectory whose name is the same as the language code. For example, given the file
394
     * "path/to/view.php" and language code "zh-CN", the localized file will be looked for as path/to/zh-CN/view.php".
395
     * If the file is not found, it will try a fallback with just a language code that is "zh" i.e. "path/to/zh/view.php".
396
     * If it is not found as well the original file will be returned.
397
     *
398
     * If the target and the source language codes are the same, the original file will be returned.
399
     *
400
     * @param string $file the original file
401
     * @param string|null $language the target language that the file should be localized to.
402
     * @param string|null $sourceLanguage the language that the original file is in.
403
     *
404
     * @return string the matching localized file, or the original file if the localized version is not found.
405
     * If the target and the source language codes are the same, the original file will be returned.
406
     */
407 12
    public function localize(string $file, ?string $language = null, ?string $sourceLanguage = null): string
408
    {
409 12
        $language = $language ?? $this->language;
410 12
        $sourceLanguage = $sourceLanguage ?? $this->sourceLanguage;
411
412 12
        if ($language === $sourceLanguage) {
413 12
            return $file;
414
        }
415 1
        $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
416 1
        if (is_file($desiredFile)) {
417 1
            return $desiredFile;
418
        }
419
420
        $language = substr($language, 0, 2);
421
        if ($language === $sourceLanguage) {
422
            return $file;
423
        }
424
        $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
425
426
        return is_file($desiredFile) ? $desiredFile : $file;
427
    }
428
429
    /**
430
     * @return bool|string the view file currently being rendered. False if no view file is being rendered.
431
     */
432 7
    public function getViewFile()
433
    {
434 7
        return empty($this->viewFiles) ? false : end($this->viewFiles)['resolved'];
435
    }
436
437
    /**
438
     * @return bool|string the requested view currently being rendered. False if no view file is being rendered.
439
     */
440 1
    protected function getRequestedViewFile()
441
    {
442 1
        return empty($this->viewFiles) ? false : end($this->viewFiles)['requested'];
443
    }
444
445
    /**
446
     * This method is invoked right before {@see renderFile()} renders a view file.
447
     *
448
     * The default implementation will trigger the {@see BeforeRender()} event. If you override this method, make sure
449
     * you call the parent implementation first.
450
     *
451
     * @param string $viewFile the view file to be rendered.
452
     * @param array $parameters the parameter array passed to the {@see render()} method.
453
     *
454
     * @return bool whether to continue rendering the view file.
455
     */
456 11
    public function beforeRender(string $viewFile, array $parameters): bool
457
    {
458 11
        $event = new BeforeRender($viewFile, $parameters);
459 11
        $event = $this->eventDispatcher->dispatch($event);
460
461 11
        return !$event->isPropagationStopped();
462
    }
463
464
    /**
465
     * This method is invoked right after {@see renderFile()} renders a view file.
466
     *
467
     * The default implementation will trigger the {@see AfterRender} event. If you override this method, make sure you
468
     * call the parent implementation first.
469
     *
470
     * @param string $viewFile the view file being rendered.
471
     * @param array $parameters the parameter array passed to the {@see render()} method.
472
     * @param string $output the rendering result of the view file.
473
     *
474
     * @return string Updated output. It will be passed to {@see renderFile()} and returned.
475
     */
476 11
    public function afterRender(string $viewFile, array $parameters, string $output): string
477
    {
478 11
        $event = new AfterRender($viewFile, $parameters, $output);
479 11
        $event = $this->eventDispatcher->dispatch($event);
480
481 11
        return $event->getResult();
482
    }
483
484
    /**
485
     * Renders dynamic content returned by the given PHP statements.
486
     *
487
     * This method is mainly used together with content caching (fragment caching and page caching) when some portions
488
     * of the content (called *dynamic content*) should not be cached. The dynamic content must be returned by some PHP
489
     * statements. You can optionally pass additional parameters that will be available as variables in the PHP
490
     * statement:.
491
     *
492
     * ```php
493
     * <?= $this->renderDynamic('return foo($myVar);', [
494
     *     'myVar' => $model->getMyComplexVar(),
495
     * ]) ?>
496
     * ```
497
     *
498
     * @param string $statements the PHP statements for generating the dynamic content.
499
     * @param array $parameters the parameters (name-value pairs) that will be extracted and made
500
     * available in the $statement context. The parameters will be stored in the cache and be reused
501
     * each time $statement is executed. You should make sure, that these are safely serializable.
502
     *
503
     * @return string the placeholder of the dynamic content, or the dynamic content if there is no active content
504
     *                cache currently.
505
     */
506
    public function renderDynamic(string $statements, array $parameters = []): string
507
    {
508
        if (!empty($parameters)) {
509
            $statements = 'extract(unserialize(\'' . str_replace(['\\', '\''], ['\\\\', '\\\''], serialize($parameters)) . '\'));' . $statements;
510
        }
511
512
        if (!empty($this->cacheStack)) {
513
            $n = count($this->dynamicPlaceholders);
514
            $placeholder = "<![CDATA[YII-DYNAMIC-$n-{$this->getPlaceholderSignature()}]]>";
515
            $this->addDynamicPlaceholder($placeholder, $statements);
516
517
            return $placeholder;
518
        }
519
520
        return $this->evaluateDynamicContent($statements);
521
    }
522
523
    /**
524
     * Get source locale.
525
     *
526
     * @return Locale
527
     */
528
    public function getSourceLocale(): Locale
529
    {
530
        if ($this->sourceLocale === null) {
531
            $this->sourceLocale = new Locale('en-US');
532
        }
533
534
        return $this->sourceLocale;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->sourceLocale could return the type null which is incompatible with the type-hinted return Yiisoft\I18n\Locale. Consider adding an additional type-check to rule them out.
Loading history...
535
    }
536
537
    /**
538
     * Set source locale.
539
     *
540
     * @param string $locale
541
     *
542
     * @return self
543
     */
544
    public function setSourceLocale(string $locale): self
545
    {
546
        $this->sourceLocale = new Locale($locale);
547
548
        return $this;
549
    }
550
551
    public function getDynamicPlaceholders(): array
552
    {
553
        return $this->dynamicPlaceholders;
554
    }
555
556
    public function setDynamicPlaceholders(array $placeholders): void
557
    {
558
        $this->dynamicPlaceholders = $placeholders;
559
    }
560
561
    public function addDynamicPlaceholder(string $name, string $statements): void
562
    {
563
        foreach ($this->cacheStack as $cache) {
564
            $cache->addDynamicPlaceholder($name, $statements);
565
        }
566
567
        $this->dynamicPlaceholders[$name] = $statements;
568
    }
569
570
    /**
571
     * Evaluates the given PHP statements.
572
     *
573
     * This method is mainly used internally to implement dynamic content feature.
574
     *
575
     * @param string $statements the PHP statements to be evaluated.
576
     *
577
     * @return mixed the return value of the PHP statements.
578
     */
579
    public function evaluateDynamicContent(string $statements)
580
    {
581
        return eval($statements);
0 ignored issues
show
introduced by
The use of eval() is discouraged.
Loading history...
582
    }
583
584
    /**
585
     * Returns a list of currently active dynamic content class instances.
586
     *
587
     * @return DynamicContentAwareInterface[] class instances supporting dynamic contents.
588
     */
589
    public function getDynamicContents(): array
590
    {
591
        return $this->cacheStack;
592
    }
593
594
    /**
595
     * Adds a class instance supporting dynamic contents to the end of a list of currently active dynamic content class
596
     * instances.
597
     *
598
     * @param DynamicContentAwareInterface $instance class instance supporting dynamic contents.
599
     */
600
    public function pushDynamicContent(DynamicContentAwareInterface $instance): void
601
    {
602
        $this->cacheStack[] = $instance;
603
    }
604
605
    /**
606
     * Removes a last class instance supporting dynamic contents from a list of currently active dynamic content class
607
     * instances.
608
     */
609
    public function popDynamicContent(): void
610
    {
611
        array_pop($this->cacheStack);
612
    }
613
614
    /**
615
     * Marks the beginning of a page.
616
     */
617 7
    public function beginPage(): void
618
    {
619 7
        ob_start();
620 7
        PHP_VERSION_ID >= 80000 ? ob_implicit_flush(false) : ob_implicit_flush(0);
621
622 7
        $this->eventDispatcher->dispatch(new PageBegin($this->getViewFile()));
0 ignored issues
show
Bug introduced by
It seems like $this->getViewFile() can also be of type boolean; however, parameter $file of Yiisoft\View\Event\PageBegin::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

622
        $this->eventDispatcher->dispatch(new PageBegin(/** @scrutinizer ignore-type */ $this->getViewFile()));
Loading history...
623 7
    }
624
625
    /**
626
     * Marks the ending of a page.
627
     */
628
    public function endPage(): void
629
    {
630
        $this->eventDispatcher->dispatch(new PageEnd($this->getViewFile()));
0 ignored issues
show
Bug introduced by
It seems like $this->getViewFile() can also be of type boolean; however, parameter $file of Yiisoft\View\Event\PageEnd::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

630
        $this->eventDispatcher->dispatch(new PageEnd(/** @scrutinizer ignore-type */ $this->getViewFile()));
Loading history...
631
        ob_end_flush();
632
    }
633
}
634