Passed
Pull Request — master (#96)
by Alexander
02:21
created

View::findTemplateFile()   B

Complexity

Conditions 7
Paths 10

Size

Total Lines 26
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 7.4822

Importance

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

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

659
        $this->eventDispatcher->dispatch(new PageBegin(/** @scrutinizer ignore-type */ $this->getViewFile()));
Loading history...
660 7
    }
661
662
    /**
663
     * Marks the ending of a page.
664
     */
665
    public function endPage(): void
666
    {
667
        $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

667
        $this->eventDispatcher->dispatch(new PageEnd(/** @scrutinizer ignore-type */ $this->getViewFile()));
Loading history...
668
        ob_end_flush();
669
    }
670
}
671