Passed
Push — master ( 2b3fea...b557be )
by Alexander
02:27
created

ViewTrait::findTemplateFile()   B

Complexity

Conditions 8
Paths 10

Size

Total Lines 26
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 8

Importance

Changes 0
Metric Value
eloc 14
c 0
b 0
f 0
dl 0
loc 26
ccs 14
cts 14
cp 1
rs 8.4444
cc 8
nc 10
nop 1
crap 8
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\View;
6
7
use InvalidArgumentException;
8
use Psr\EventDispatcher\EventDispatcherInterface;
9
use Psr\EventDispatcher\StoppableEventInterface;
10
use RuntimeException;
11
use Throwable;
12
use Yiisoft\View\Event\AfterRenderEventInterface;
13
use Yiisoft\View\Exception\ViewNotFoundException;
14
15
use function array_key_exists;
16
use function array_merge;
17
use function array_pop;
18
use function basename;
19
use function crc32;
20
use function dechex;
21
use function dirname;
22
use function end;
23
use function func_get_args;
24
use function is_file;
25
use function pathinfo;
26
use function substr;
27
28
/**
29
 * ViewTrait could be used as a base implementation of {@see ViewInterface}.
30
 *
31
 * @internal
32
 */
33
trait ViewTrait
34
{
35
    private EventDispatcherInterface $eventDispatcher;
36
37
    private string $basePath;
38
    private ?Theme $theme = null;
39
    private ?ViewContextInterface $context = null;
40
    private string $placeholderSignature;
41
    private string $language = 'en';
42
    private string $sourceLanguage = 'en';
43
    private string $defaultExtension = 'php';
44
45
    /**
46
     * @var array A list of available renderers indexed by their corresponding
47
     * supported file extensions.
48
     * @psalm-var array<string, TemplateRendererInterface>
49
     */
50
    private array $renderers = [];
51
52
    /**
53
     * @var array Parameters that are common for all view templates.
54
     * @psalm-var array<string, mixed>
55
     */
56
    private array $parameters = [];
57
58
    /**
59
     * @var array Named content blocks that are common for all view templates.
60
     * @psalm-var array<string, string>
61
     */
62
    private array $blocks = [];
63
64
    /**
65
     * @var array The view files currently being rendered. There may be multiple view files being
66
     * rendered at a moment because one view may be rendered within another.
67
     *
68
     * @psalm-var array<array-key, array<string, string>>
69
     */
70
    private array $viewFiles = [];
71
72
    /**
73
     * @param string $basePath The full path to the base directory of views.
74
     * @param EventDispatcherInterface $eventDispatcher The event dispatcher instance.
75
     */
76 105
    public function __construct(string $basePath, EventDispatcherInterface $eventDispatcher)
77
    {
78 105
        $this->basePath = $basePath;
79 105
        $this->eventDispatcher = $eventDispatcher;
80 105
        $this->setPlaceholderSalt(__DIR__);
81 105
    }
82
83
    /**
84
     * Returns a new instance with the specified theme instance.
85
     *
86
     * @param Theme $theme The theme instance.
87
     *
88
     * @return static
89
     */
90 2
    public function withTheme(Theme $theme): self
91
    {
92 2
        $new = clone $this;
93 2
        $new->theme = $theme;
94 2
        return $new;
95
    }
96
97
    /**
98
     * Returns a new instance with the specified renderers.
99
     *
100
     * @param array $renderers A list of available renderers indexed by their
101
     * corresponding supported file extensions.
102
     *
103
     * ```php
104
     * $view = $view->withRenderers(['twig' => new \Yiisoft\Yii\Twig\ViewRenderer($environment)]);
105
     * ```
106
     *
107
     * If no renderer is available for the given view file, the view file will be treated as a normal PHP
108
     * and rendered via {@see PhpTemplateRenderer}.
109
     *
110
     * @psalm-param array<string, TemplateRendererInterface> $renderers
111
     *
112
     * @return static
113
     */
114 1
    public function withRenderers(array $renderers): self
115
    {
116 1
        $new = clone $this;
117 1
        $new->renderers = $renderers;
118 1
        return $new;
119
    }
120
121
    /**
122
     * Returns a new instance with the specified language.
123
     *
124
     * @param string $language The language.
125
     *
126
     * @return static
127
     */
128 1
    public function withLanguage(string $language): self
129
    {
130 1
        $new = clone $this;
131 1
        $new->language = $language;
132 1
        return $new;
133
    }
134
135
    /**
136
     * Returns a new instance with the specified source language.
137
     *
138
     * @param string $language The source language.
139
     *
140
     * @return static
141
     */
142 1
    public function withSourceLanguage(string $language): self
143
    {
144 1
        $new = clone $this;
145 1
        $new->sourceLanguage = $language;
146 1
        return $new;
147
    }
148
149
    /**
150
     * Returns a new instance with the specified default view file extension.
151
     *
152
     * @param string $defaultExtension The default view file extension. Default is "php".
153
     * This will be appended to view file names if they don't have file extensions.
154
     *
155
     * @return static
156
     */
157 2
    public function withDefaultExtension(string $defaultExtension): self
158
    {
159 2
        $new = clone $this;
160 2
        $new->defaultExtension = $defaultExtension;
161 2
        return $new;
162
    }
163
164
    /**
165
     * Returns a new instance with the specified view context instance.
166
     *
167
     * @param ViewContextInterface $context The context under which the {@see renderFile()} method is being invoked.
168
     *
169
     * @return static
170
     */
171 4
    public function withContext(ViewContextInterface $context): self
172
    {
173 4
        $new = clone $this;
174 4
        $new->context = $context;
175 4
        $new->viewFiles = [];
176 4
        return $new;
177
    }
178
179
    /**
180
     * Gets the base path to the view directory.
181
     *
182
     * @return string The base view path.
183
     */
184 1
    public function getBasePath(): string
185
    {
186 1
        return $this->basePath;
187
    }
188
189
    /**
190
     * Gets the default view file extension.
191
     *
192
     * @return string The default view file extension.
193
     */
194 1
    public function getDefaultExtension(): string
195
    {
196 1
        return $this->defaultExtension;
197
    }
198
199
    /**
200
     * Gets the theme instance, or null if no theme has been set.
201
     *
202
     * @return Theme The theme instance, or null if no theme has been set.
203
     */
204 2
    public function getTheme(): ?Theme
205
    {
206 2
        return $this->theme;
207
    }
208
209
    /**
210
     * Sets a common parameters that is accessible in all view templates.
211
     *
212
     * @param array $parameters Parameters that are common for all view templates.
213
     *
214
     * @psalm-param array<string, mixed> $parameters
215
     *
216
     * @return static
217
     *
218
     * @see setParameter()
219
     */
220 3
    public function setParameters(array $parameters): self
221
    {
222
        /** @var mixed $value */
223 3
        foreach ($parameters as $id => $value) {
224 1
            $this->setParameter($id, $value);
225
        }
226 3
        return $this;
227
    }
228
229
    /**
230
     * Sets a common parameter that is accessible in all view templates.
231
     *
232
     * @param string $id The unique identifier of the parameter.
233
     * @param mixed $value The value of the parameter.
234
     *
235
     * @return static
236
     */
237 5
    public function setParameter(string $id, $value): self
238
    {
239 5
        $this->parameters[$id] = $value;
240 5
        return $this;
241
    }
242
243
    /**
244
     * Removes a common parameter.
245
     *
246
     * @param string $id The unique identifier of the parameter.
247
     */
248 1
    public function removeParameter(string $id): void
249
    {
250 1
        unset($this->parameters[$id]);
251 1
    }
252
253
    /**
254
     * Gets a common parameter value by ID.
255
     *
256
     * @param string $id The unique identifier of the parameter.
257
     * @param mixed $default The default value to be returned if the specified parameter does not exist.
258
     *
259
     * @throws InvalidArgumentException If specified parameter does not exist and not passed default value.
260
     *
261
     * @return mixed The value of the parameter.
262
     */
263 3
    public function getParameter(string $id)
264
    {
265 3
        if (isset($this->parameters[$id])) {
266 1
            return $this->parameters[$id];
267
        }
268
269 3
        $args = func_get_args();
270 3
        if (array_key_exists(1, $args)) {
271 1
            return $args[1];
272
        }
273
274 2
        throw new InvalidArgumentException('Parameter "' . $id . '" not found.');
275
    }
276
277
    /**
278
     * Checks the existence of a common parameter by ID.
279
     *
280
     * @param string $id The unique identifier of the parameter.
281
     *
282
     * @return bool Whether a custom parameter that is common for all view templates exists.
283
     */
284 1
    public function hasParameter(string $id): bool
285
    {
286 1
        return isset($this->parameters[$id]);
287
    }
288
289
    /**
290
     * Sets a content block.
291
     *
292
     * @param string $id The unique identifier of the block.
293
     * @param string $content The content of the block.
294
     *
295
     * @return static
296
     */
297 3
    public function setBlock(string $id, string $content): self
298
    {
299 3
        $this->blocks[$id] = $content;
300 3
        return $this;
301
    }
302
303
    /**
304
     * Removes a content block.
305
     *
306
     * @param string $id The unique identifier of the block.
307
     */
308 1
    public function removeBlock(string $id): void
309
    {
310 1
        unset($this->blocks[$id]);
311 1
    }
312
313
    /**
314
     * Gets content of the block by ID.
315
     *
316
     * @param string $id The unique identifier of the block.
317
     *
318
     * @return string The content of the block.
319
     */
320 2
    public function getBlock(string $id): string
321
    {
322 2
        if (isset($this->blocks[$id])) {
323 1
            return $this->blocks[$id];
324
        }
325
326 2
        throw new InvalidArgumentException('Block "' . $id . '" not found.');
327
    }
328
329
    /**
330
     * Checks the existence of a content block by ID.
331
     *
332
     * @param string $id The unique identifier of the block.
333
     *
334
     * @return bool Whether a content block exists.
335
     */
336 1
    public function hasBlock(string $id): bool
337
    {
338 1
        return isset($this->blocks[$id]);
339
    }
340
341
    /**
342
     * Gets the view file currently being rendered.
343
     *
344
     * @return string|null The view file currently being rendered. `null` if no view file is being rendered.
345
     */
346 1
    public function getViewFile(): ?string
347
    {
348
        /** @psalm-suppress InvalidArrayOffset */
349 1
        return empty($this->viewFiles) ? null : end($this->viewFiles)['resolved'];
350
    }
351
352
    /**
353
     * Gets the placeholder signature.
354
     *
355
     * @return string The placeholder signature.
356
     */
357 47
    public function getPlaceholderSignature(): string
358
    {
359 47
        return $this->placeholderSignature;
360
    }
361
362
    /**
363
     * Sets a salt for the placeholder signature {@see getPlaceholderSignature()}.
364
     *
365
     * @param string $salt The placeholder salt.
366
     *
367
     * @return static
368
     */
369 105
    public function setPlaceholderSalt(string $salt): self
370
    {
371 105
        $this->placeholderSignature = dechex(crc32($salt));
372 105
        return $this;
373
    }
374
375
    /**
376
     * Renders a view.
377
     *
378
     * The view to be rendered can be specified in one of the following formats:
379
     *
380
     * - The name of the view starting with a slash to join the base path {@see getBasePath()} (e.g. "/site/index").
381
     * - The name of the view without the starting slash (e.g. "site/index"). The corresponding view file will be
382
     *   looked for under the {@see ViewContextInterface::getViewPath()} of the context set via {@see withContext()}.
383
     *   If the context instance was not set {@see withContext()}, it will be looked for under the directory containing
384
     *   the view currently being rendered (i.e., this happens when rendering a view within another view).
385
     *
386
     * @param string $view The view name.
387
     * @param array $parameters The parameters (name-value pairs) that will be extracted and made available in the view
388
     * file.
389
     *
390
     * @throws RuntimeException If the view cannot be resolved.
391
     * @throws ViewNotFoundException If the view file does not exist.
392
     * @throws Throwable
393
     *
394
     * {@see renderFile()}
395
     *
396
     * @return string The rendering result.
397
     */
398 50
    public function render(string $view, array $parameters = []): string
399
    {
400 50
        $viewFile = $this->findTemplateFile($view);
401
402 49
        return $this->renderFile($viewFile, $parameters);
403
    }
404
405
    /**
406
     * Renders a view file.
407
     *
408
     * If the theme was set {@see withTheme()}, it will try to render the themed version of the view file
409
     * as long as it is available.
410
     *
411
     * If the renderer was set {@see withRenderers()}, the method will use it to render the view file. Otherwise,
412
     * it will simply include the view file as a normal PHP file, capture its output and return it as a string.
413
     *
414
     * @param string $viewFile The full absolute path of the view file.
415
     * @param array $parameters The parameters (name-value pairs) that will be extracted and made available in the view
416
     * file.
417
     *
418
     * @throws Throwable
419
     * @throws ViewNotFoundException If the view file does not exist
420
     *
421
     * @return string The rendering result.
422
     */
423 53
    public function renderFile(string $viewFile, array $parameters = []): string
424
    {
425 53
        $parameters = array_merge($this->parameters, $parameters);
426
427
        // TODO: these two match now
428 53
        $requestedFile = $viewFile;
429
430 53
        if ($this->theme !== null) {
431 1
            $viewFile = $this->theme->applyTo($viewFile);
432
        }
433
434 53
        if (is_file($viewFile)) {
435 52
            $viewFile = $this->localize($viewFile);
436
        } else {
437 1
            throw new ViewNotFoundException("The view file \"$viewFile\" does not exist.");
438
        }
439
440 52
        $output = '';
441 52
        $this->viewFiles[] = [
442 52
            'resolved' => $viewFile,
443 52
            'requested' => $requestedFile,
444
        ];
445
446 52
        if ($this->beforeRender($viewFile, $parameters)) {
447 52
            $ext = pathinfo($viewFile, PATHINFO_EXTENSION);
448 52
            $renderer = $this->renderers[$ext] ?? new PhpTemplateRenderer();
449 52
            $output = $renderer->render($this, $viewFile, $parameters);
0 ignored issues
show
Bug introduced by
$this of type Yiisoft\View\ViewTrait is incompatible with the type Yiisoft\View\ViewInterface expected by parameter $view of Yiisoft\View\PhpTemplateRenderer::render(). ( Ignorable by Annotation )

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

449
            $output = $renderer->render(/** @scrutinizer ignore-type */ $this, $viewFile, $parameters);
Loading history...
450 52
            $output = $this->afterRender($viewFile, $parameters, $output);
451
        }
452
453 52
        array_pop($this->viewFiles);
454
455 52
        return $output;
456
    }
457
458
    /**
459
     * Returns the localized version of a specified file.
460
     *
461
     * The searching is based on the specified language code. In particular, a file with the same name will be looked
462
     * for under the subdirectory whose name is the same as the language code. For example, given the file
463
     * "path/to/view.php" and language code "zh-CN", the localized file will be looked for as "path/to/zh-CN/view.php".
464
     * If the file is not found, it will try a fallback with just a language code that is "zh"
465
     * i.e. "path/to/zh/view.php".
466
     * If it is not found as well the original file will be returned.
467
     *
468
     * If the target and the source language codes are the same, the original file will be returned.
469
     *
470
     * @param string $file The original file
471
     * @param string|null $language The target language that the file should be localized to.
472
     * @param string|null $sourceLanguage The language that the original file is in.
473
     *
474
     * @return string The matching localized file, or the original file if the localized version is not found.
475
     * If the target and the source language codes are the same, the original file will be returned.
476
     */
477 54
    public function localize(string $file, ?string $language = null, ?string $sourceLanguage = null): string
478
    {
479 54
        $language = $language ?? $this->language;
480 54
        $sourceLanguage = $sourceLanguage ?? $this->sourceLanguage;
481
482 54
        if ($language === $sourceLanguage) {
483 54
            return $file;
484
        }
485
486 2
        $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
487
488 2
        if (is_file($desiredFile)) {
489 2
            return $desiredFile;
490
        }
491
492 1
        $language = substr($language, 0, 2);
493
494 1
        if ($language === $sourceLanguage) {
495 1
            return $file;
496
        }
497
498 1
        $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
499 1
        return is_file($desiredFile) ? $desiredFile : $file;
500
    }
501
502
    /**
503
     * Creates an event that occurs before rendering.
504
     *
505
     * @param string $viewFile The view file to be rendered.
506
     * @param array $parameters The parameter array passed to the {@see renderFile()} method.
507
     *
508
     * @return StoppableEventInterface The stoppable event instance.
509
     */
510
    abstract protected function createBeforeRenderEvent(string $viewFile, array $parameters): StoppableEventInterface;
511
512
    /**
513
     * Creates an event that occurs after rendering.
514
     *
515
     * @param string $viewFile The view file being rendered.
516
     * @param array $parameters The parameter array passed to the {@see renderFile()} method.
517
     * @param string $result The rendering result of the view file.
518
     *
519
     * @return AfterRenderEventInterface The event instance.
520
     */
521
    abstract protected function createAfterRenderEvent(
522
        string $viewFile,
523
        array $parameters,
524
        string $result
525
    ): AfterRenderEventInterface;
526
527
    /**
528
     * This method is invoked right before {@see renderFile()} renders a view file.
529
     *
530
     * The default implementations will trigger the {@see \Yiisoft\View\Event\View\BeforeRender}
531
     * or {@see \Yiisoft\View\Event\WebView\BeforeRender} event. If you override this method,
532
     * make sure you call the parent implementation first.
533
     *
534
     * @param string $viewFile The view file to be rendered.
535
     * @param array $parameters The parameter array passed to the {@see renderFile()} method.
536
     *
537
     * @return bool Whether to continue rendering the view file.
538
     */
539 52
    private function beforeRender(string $viewFile, array $parameters): bool
540
    {
541 52
        $event = $this->createBeforeRenderEvent($viewFile, $parameters);
542 52
        $event = $this->eventDispatcher->dispatch($event);
543
        /** @var StoppableEventInterface $event */
544 52
        return !$event->isPropagationStopped();
545
    }
546
547
    /**
548
     * This method is invoked right after {@see renderFile()} renders a view file.
549
     *
550
     * The default implementations will trigger the {@see \Yiisoft\View\Event\View\AfterRender}
551
     * or {@see \Yiisoft\View\Event\WebView\AfterRender} event. If you override this method,
552
     * make sure you call the parent implementation first.
553
     *
554
     * @param string $viewFile The view file being rendered.
555
     * @param array $parameters The parameter array passed to the {@see renderFile()} method.
556
     * @param string $result The rendering result of the view file.
557
     *
558
     * @return string Updated output. It will be passed to {@see renderFile()} and returned.
559
     */
560 52
    private function afterRender(string $viewFile, array $parameters, string $result): string
561
    {
562 52
        $event = $this->createAfterRenderEvent($viewFile, $parameters, $result);
563
564
        /** @var AfterRenderEventInterface $event */
565 52
        $event = $this->eventDispatcher->dispatch($event);
566
567 52
        return $event->getResult();
568
    }
569
570
    /**
571
     * Finds the view file based on the given view name.
572
     *
573
     * @param string $view The view name of the view file. Please refer to
574
     * {@see render()} on how to specify this parameter.
575
     *
576
     * @throws RuntimeException If a relative view name is given while there is no active context to determine the
577
     * corresponding view file.
578
     *
579
     * @return string The view file path. Note that the file may not exist.
580
     */
581 52
    private function findTemplateFile(string $view): string
582
    {
583 52
        if ($view !== '' && $view[0] === '/') {
584
            // path relative to basePath e.g. "/layouts/main"
585 49
            $file = $this->basePath . '/' . ltrim($view, '/');
586 5
        } elseif (($currentViewFile = $this->getRequestedViewFile()) !== null) {
587
            // path relative to currently rendered view
588 2
            $file = dirname($currentViewFile) . '/' . $view;
589 4
        } elseif ($this->context instanceof ViewContextInterface) {
590
            // path provided by context
591 3
            $file = $this->context->getViewPath() . '/' . $view;
592
        } else {
593 1
            throw new RuntimeException("Unable to resolve view file for view \"$view\": no active view context.");
594
        }
595
596 51
        if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
597 45
            return $file;
598
        }
599
600 6
        $path = $file . '.' . $this->defaultExtension;
601
602 6
        if ($this->defaultExtension !== 'php' && !is_file($path)) {
603 1
            $path = $file . '.php';
604
        }
605
606 6
        return $path;
607
    }
608
609
    /**
610
     * @return string|null The requested view currently being rendered. `null` if no view file is being rendered.
611
     */
612 5
    private function getRequestedViewFile(): ?string
613
    {
614
        /** @psalm-suppress InvalidArrayOffset */
615 5
        return empty($this->viewFiles) ? null : end($this->viewFiles)['requested'];
616
    }
617
}
618