Passed
Pull Request — master (#226)
by Rustam
02:44
created

ViewTrait::getContext()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
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
use Yiisoft\View\State\LocaleState;
15
16
use function array_merge;
17
use function array_pop;
18
use function basename;
19
use function call_user_func_array;
20
use function crc32;
21
use function dechex;
22
use function dirname;
23
use function end;
24
use function func_get_args;
25
use function is_file;
26
use function pathinfo;
27
use function substr;
28
29
/**
30
 * `ViewTrait` could be used as a base implementation of {@see ViewInterface}.
31
 *
32
 * @internal
33
 */
34
trait ViewTrait
35
{
36
    private EventDispatcherInterface $eventDispatcher;
37
38
    private string $basePath;
39
    private ?ViewContextInterface $context = null;
40
    private string $placeholderSignature;
41
    private string $sourceLocale = 'en';
42
    private string $defaultExtension = 'php';
43
44
    /**
45
     * @var array A list of available renderers indexed by their corresponding
46
     * supported file extensions.
47
     * @psalm-var array<string, TemplateRendererInterface>
48
     */
49
    private array $renderers = [];
50
51
    /**
52
     * @var array The view files currently being rendered. There may be multiple view files being
53
     * rendered at a moment because one view may be rendered within another.
54
     *
55
     * @psalm-var array<array-key, array<string, string>>
56
     */
57
    private array $viewFiles = [];
58
59
    /**
60
     * Returns a new instance with specified base path to the view directory.
61
     *
62
     * @param string $basePath The base path to the view directory.
63
     */
64 2
    public function withBasePath(string $basePath): static
65
    {
66 2
        $new = clone $this;
67 2
        $new->basePath = $basePath;
68 2
        return $new;
69
    }
70
71
    /**
72
     * Returns a new instance with the specified renderers.
73
     *
74
     * @param array $renderers A list of available renderers indexed by their
75
     * corresponding supported file extensions.
76
     *
77
     * ```php
78
     * $view = $view->withRenderers(['twig' => new \Yiisoft\View\Twig\TemplateRenderer($environment)]);
79
     * ```
80
     *
81
     * If no renderer is available for the given view file, the view file will be treated as a normal PHP
82
     * and rendered via {@see PhpTemplateRenderer}.
83
     *
84
     * @psalm-param array<string, TemplateRendererInterface> $renderers
85
     */
86 3
    public function withRenderers(array $renderers): static
87
    {
88 3
        $new = clone $this;
89 3
        $new->renderers = $renderers;
90 3
        return $new;
91
    }
92
93
    /**
94
     * Returns a new instance with the specified source locale.
95
     *
96
     * @param string $locale The source locale.
97
     */
98 3
    public function withSourceLocale(string $locale): static
99
    {
100 3
        $new = clone $this;
101 3
        $new->sourceLocale = $locale;
102 3
        return $new;
103
    }
104
105
    /**
106
     * Returns a new instance with the specified default view file extension.
107
     *
108
     * @param string $defaultExtension The default view file extension. Default is "php".
109
     * This will be appended to view file names if they don't have file extensions.
110
     */
111 4
    public function withDefaultExtension(string $defaultExtension): static
112
    {
113 4
        $new = clone $this;
114 4
        $new->defaultExtension = $defaultExtension;
115 4
        return $new;
116
    }
117
118
    /**
119
     * Returns a new instance with the specified view context instance.
120
     *
121
     * @param ViewContextInterface $context The context under which the {@see renderFile()} method is being invoked.
122
     */
123 6
    public function withContext(ViewContextInterface $context): static
124
    {
125 6
        $new = clone $this;
126 6
        $new->context = $context;
127 6
        $new->viewFiles = [];
128 6
        return $new;
129
    }
130
131
    /**
132
     * Returns a new instance with the specified view context path.
133
     *
134
     * @param string $path The context path under which the {@see renderFile()} method is being invoked.
135
     */
136 2
    public function withContextPath(string $path): static
137
    {
138 2
        return $this->withContext(new ViewContext($path));
139
    }
140
141
    /**
142
     * Returns a new instance with specified salt for the placeholder signature {@see getPlaceholderSignature()}.
143
     *
144
     * @param string $salt The placeholder salt.
145
     */
146 2
    public function withPlaceholderSalt(string $salt): static
147
    {
148 2
        $new = clone $this;
149 2
        $new->setPlaceholderSalt($salt);
150 2
        return $new;
151
    }
152
153
    /**
154
     * Set the specified locale code.
155
     *
156
     * @param string $locale The locale code.
157
     */
158 2
    public function setLocale(string $locale): static
159
    {
160 2
        $this->localeState->setLocale($locale);
161 2
        return $this;
162
    }
163
164
    /**
165
     * Set the specified locale code.
166
     *
167
     * @param string $locale The locale code.
168
     */
169 3
    public function withLocale(string $locale): static
170
    {
171 3
        $new = clone $this;
172 3
        $new->localeState = new LocaleState($locale);
0 ignored issues
show
Bug Best Practice introduced by
The property localeState does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
173
174 3
        return $new;
175
    }
176
177
    /**
178
     * Gets the base path to the view directory.
179
     *
180
     * @return string The base view path.
181
     */
182 2
    public function getBasePath(): string
183
    {
184 2
        return $this->basePath;
185
    }
186
187
    /**
188
     * Gets the context instance, or `null` if no context has been set.
189
     */
190 1
    public function getContext(): ?ViewContextInterface
191
    {
192 1
        return $this->context;
193
    }
194
195
    /**
196
     * Gets the default view file extension.
197
     *
198
     * @return string The default view file extension.
199
     */
200 1
    public function getDefaultExtension(): string
201
    {
202 1
        return $this->defaultExtension;
203
    }
204
205
    /**
206
     * Gets the theme instance, or `null` if no theme has been set.
207
     *
208
     * @return Theme|null The theme instance, or `null` if no theme has been set.
209
     */
210 60
    public function getTheme(): ?Theme
211
    {
212 60
        return $this->state->getTheme();
213
    }
214
215
    /**
216
     * Set the specified theme instance.
217
     *
218
     * @param Theme|null $theme The theme instance or `null` for reset theme.
219
     */
220 1
    public function setTheme(?Theme $theme): static
221
    {
222 1
        $this->state->setTheme($theme);
223 1
        return $this;
224
    }
225
226
    /**
227
     * Sets a common parameters that is accessible in all view templates.
228
     *
229
     * @param array $parameters Parameters that are common for all view templates.
230
     *
231
     * @psalm-param array<string, mixed> $parameters
232
     *
233
     * @see setParameter()
234
     */
235 5
    public function setParameters(array $parameters): static
236
    {
237 5
        $this->state->setParameters($parameters);
238 5
        return $this;
239
    }
240
241
    /**
242
     * Sets a common parameter that is accessible in all view templates.
243
     *
244
     * @param string $id The unique identifier of the parameter.
245
     * @param mixed $value The value of the parameter.
246
     */
247 12
    public function setParameter(string $id, mixed $value): static
248
    {
249 12
        $this->state->setParameter($id, $value);
250 12
        return $this;
251
    }
252
253
    /**
254
     * Add values to end of common array parameter. If specified parameter does not exist or him is not array,
255
     * then parameter will be added as empty array.
256
     *
257
     * @param string $id The unique identifier of the parameter.
258
     * @param mixed ...$value Value(s) for add to end of array parameter.
259
     *
260
     * @throws InvalidArgumentException When specified parameter already exists and is not an array.
261
     */
262 6
    public function addToParameter(string $id, mixed ...$value): static
263
    {
264 6
        $this->state->addToParameter($id, ...$value);
265 5
        return $this;
266
    }
267
268
    /**
269
     * Removes a common parameter.
270
     *
271
     * @param string $id The unique identifier of the parameter.
272
     */
273 3
    public function removeParameter(string $id): static
274
    {
275 3
        $this->state->removeParameter($id);
276 3
        return $this;
277
    }
278
279
    /**
280
     * Gets a common parameter value by ID.
281
     *
282
     * @param string $id The unique identifier of the parameter.
283
     * @param mixed $default The default value to be returned if the specified parameter does not exist.
284
     *
285
     * @throws InvalidArgumentException If specified parameter does not exist and not passed default value.
286
     *
287
     * @return mixed The value of the parameter.
288
     */
289 8
    public function getParameter(string $id)
290
    {
291 8
        return call_user_func_array([$this->state, 'getParameter'], func_get_args());
292
    }
293
294
    /**
295
     * Checks the existence of a common parameter by ID.
296
     *
297
     * @param string $id The unique identifier of the parameter.
298
     *
299
     * @return bool Whether a custom parameter that is common for all view templates exists.
300
     */
301 5
    public function hasParameter(string $id): bool
302
    {
303 5
        return $this->state->hasParameter($id);
304
    }
305
306
    /**
307
     * Sets a content block.
308
     *
309
     * @param string $id The unique identifier of the block.
310
     * @param string $content The content of the block.
311
     */
312 7
    public function setBlock(string $id, string $content): static
313
    {
314 7
        $this->state->setBlock($id, $content);
315 7
        return $this;
316
    }
317
318
    /**
319
     * Removes a content block.
320
     *
321
     * @param string $id The unique identifier of the block.
322
     */
323 3
    public function removeBlock(string $id): static
324
    {
325 3
        $this->state->removeBlock($id);
326 3
        return $this;
327
    }
328
329
    /**
330
     * Gets content of the block by ID.
331
     *
332
     * @param string $id The unique identifier of the block.
333
     *
334
     * @return string The content of the block.
335
     */
336 2
    public function getBlock(string $id): string
337
    {
338 2
        return $this->state->getBlock($id);
339
    }
340
341
    /**
342
     * Checks the existence of a content block by ID.
343
     *
344
     * @param string $id The unique identifier of the block.
345
     *
346
     * @return bool Whether a content block exists.
347
     */
348 5
    public function hasBlock(string $id): bool
349
    {
350 5
        return $this->state->hasBlock($id);
351
    }
352
353
    /**
354
     * Gets the view file currently being rendered.
355
     *
356
     * @return string|null The view file currently being rendered. `null` if no view file is being rendered.
357
     */
358 5
    public function getViewFile(): ?string
359
    {
360
        /** @psalm-suppress InvalidArrayOffset */
361 5
        return empty($this->viewFiles) ? null : end($this->viewFiles)['resolved'];
362
    }
363
364
    /**
365
     * Gets the placeholder signature.
366
     *
367
     * @return string The placeholder signature.
368
     */
369 49
    public function getPlaceholderSignature(): string
370
    {
371 49
        return $this->placeholderSignature;
372
    }
373
374
    /**
375
     * Renders a view.
376
     *
377
     * The view to be rendered can be specified in one of the following formats:
378
     *
379
     * - The name of the view starting with a slash to join the base path {@see getBasePath()} (e.g. "/site/index").
380
     * - The name of the view without the starting slash (e.g. "site/index"). The corresponding view file will be
381
     *   looked for under the {@see ViewContextInterface::getViewPath()} of the context set via {@see withContext()}.
382
     *   If the context instance was not set {@see withContext()}, it will be looked for under the directory containing
383
     *   the view currently being rendered (i.e., this happens when rendering a view within another view).
384
     *
385
     * @param string $view The view name.
386
     * @param array $parameters The parameters (name-value pairs) that will be extracted and made available in the view
387
     * file.
388
     *
389
     * @throws RuntimeException If the view cannot be resolved.
390
     * @throws ViewNotFoundException If the view file does not exist.
391
     * @throws Throwable
392
     *
393
     * {@see renderFile()}
394
     *
395
     * @return string The rendering result.
396
     */
397 56
    public function render(string $view, array $parameters = []): string
398
    {
399 56
        $viewFile = $this->findTemplateFile($view);
400
401 55
        return $this->renderFile($viewFile, $parameters);
402
    }
403
404
    /**
405
     * Renders a view file.
406
     *
407
     * If the theme was set {@see setTheme()}, it will try to render the themed version of the view file
408
     * as long as it is available.
409
     *
410
     * If the renderer was set {@see withRenderers()}, the method will use it to render the view file. Otherwise,
411
     * it will simply include the view file as a normal PHP file, capture its output and return it as a string.
412
     *
413
     * @param string $viewFile The full absolute path of the view file.
414
     * @param array $parameters The parameters (name-value pairs) that will be extracted and made available in the view
415
     * file.
416
     *
417
     * @throws Throwable
418
     * @throws ViewNotFoundException If the view file does not exist
419
     *
420
     * @return string The rendering result.
421
     */
422 60
    public function renderFile(string $viewFile, array $parameters = []): string
423
    {
424 60
        $parameters = array_merge($this->state->getParameters(), $parameters);
425
426
        // TODO: these two match now
427 60
        $requestedFile = $viewFile;
428
429 60
        $theme = $this->getTheme();
430 60
        if ($theme !== null) {
431 1
            $viewFile = $theme->applyTo($viewFile);
432
        }
433
434 60
        if (is_file($viewFile)) {
435 59
            $viewFile = $this->localize($viewFile);
436
        } else {
437 1
            throw new ViewNotFoundException("The view file \"$viewFile\" does not exist.");
438
        }
439
440 59
        $output = '';
441 59
        $this->viewFiles[] = [
442 59
            'resolved' => $viewFile,
443 59
            'requested' => $requestedFile,
444 59
        ];
445
446 59
        if ($this->beforeRender($viewFile, $parameters)) {
447 59
            $ext = pathinfo($viewFile, PATHINFO_EXTENSION);
448 59
            $renderer = $this->renderers[$ext] ?? new PhpTemplateRenderer();
449 59
            $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 58
            $output = $this->afterRender($viewFile, $parameters, $output);
451
        }
452
453 58
        array_pop($this->viewFiles);
454
455 58
        return $output;
456
    }
457
458
    /**
459
     * Returns the localized version of a specified file.
460
     *
461
     * The searching is based on the specified locale code. In particular, a file with the same name will be looked
462
     * for under the subdirectory whose name is the same as the locale code. For example, given the file
463
     * "path/to/view.php" and locale 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 locale 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 locale codes are the same, the original file will be returned.
469
     *
470
     * @param string $file The original file
471
     * @param string|null $locale The target locale that the file should be localized to.
472
     * @param string|null $sourceLocale The locale 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 locale codes are the same, the original file will be returned.
476
     */
477 62
    public function localize(string $file, ?string $locale = null, ?string $sourceLocale = null): string
478
    {
479 62
        $locale ??= $this->localeState->getLocale();
480 62
        $sourceLocale ??= $this->sourceLocale;
481
482 62
        if ($locale === $sourceLocale) {
483 60
            return $file;
484
        }
485
486 6
        $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $locale . DIRECTORY_SEPARATOR . basename($file);
487
488 6
        if (is_file($desiredFile)) {
489 6
            return $desiredFile;
490
        }
491
492 1
        $locale = substr($locale, 0, 2);
493
494 1
        if ($locale === $sourceLocale) {
495 1
            return $file;
496
        }
497
498 1
        $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $locale . DIRECTORY_SEPARATOR . basename($file);
499 1
        return is_file($desiredFile) ? $desiredFile : $file;
500
    }
501
502
    /**
503
     * Clears the data for working with the event loop.
504
     */
505 2
    public function clear(): void
506
    {
507 2
        $this->viewFiles = [];
508 2
        $this->state->clear();
509 2
        $this->localeState = new LocaleState();
0 ignored issues
show
Bug Best Practice introduced by
The property localeState does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
510
    }
511
512
    /**
513
     * Creates an event that occurs before rendering.
514
     *
515
     * @param string $viewFile The view file to be rendered.
516
     * @param array $parameters The parameter array passed to the {@see renderFile()} method.
517
     *
518
     * @return StoppableEventInterface The stoppable event instance.
519
     */
520
    abstract protected function createBeforeRenderEvent(string $viewFile, array $parameters): StoppableEventInterface;
521
522
    /**
523
     * Creates an event that occurs after rendering.
524
     *
525
     * @param string $viewFile The view file being rendered.
526
     * @param array $parameters The parameter array passed to the {@see renderFile()} method.
527
     * @param string $result The rendering result of the view file.
528
     *
529
     * @return AfterRenderEventInterface The event instance.
530
     */
531
    abstract protected function createAfterRenderEvent(
532
        string $viewFile,
533
        array $parameters,
534
        string $result
535
    ): AfterRenderEventInterface;
536
537
    /**
538
     * This method is invoked right before {@see renderFile()} renders a view file.
539
     *
540
     * The default implementations will trigger the {@see \Yiisoft\View\Event\View\BeforeRender}
541
     * or {@see \Yiisoft\View\Event\WebView\BeforeRender} event. If you override this method,
542
     * make sure you call the parent implementation first.
543
     *
544
     * @param string $viewFile The view file to be rendered.
545
     * @param array $parameters The parameter array passed to the {@see renderFile()} method.
546
     *
547
     * @return bool Whether to continue rendering the view file.
548
     */
549 59
    private function beforeRender(string $viewFile, array $parameters): bool
550
    {
551 59
        $event = $this->createBeforeRenderEvent($viewFile, $parameters);
552 59
        $event = $this->eventDispatcher->dispatch($event);
553
        /** @var StoppableEventInterface $event */
554 59
        return !$event->isPropagationStopped();
555
    }
556
557
    /**
558
     * This method is invoked right after {@see renderFile()} renders a view file.
559
     *
560
     * The default implementations will trigger the {@see \Yiisoft\View\Event\View\AfterRender}
561
     * or {@see \Yiisoft\View\Event\WebView\AfterRender} event. If you override this method,
562
     * make sure you call the parent implementation first.
563
     *
564
     * @param string $viewFile The view file being rendered.
565
     * @param array $parameters The parameter array passed to the {@see renderFile()} method.
566
     * @param string $result The rendering result of the view file.
567
     *
568
     * @return string Updated output. It will be passed to {@see renderFile()} and returned.
569
     */
570 58
    private function afterRender(string $viewFile, array $parameters, string $result): string
571
    {
572 58
        $event = $this->createAfterRenderEvent($viewFile, $parameters, $result);
573
574
        /** @var AfterRenderEventInterface $event */
575 58
        $event = $this->eventDispatcher->dispatch($event);
576
577 58
        return $event->getResult();
578
    }
579
580 125
    private function setPlaceholderSalt(string $salt): void
581
    {
582 125
        $this->placeholderSignature = dechex(crc32($salt));
583
    }
584
585
    /**
586
     * Finds the view file based on the given view name.
587
     *
588
     * @param string $view The view name of the view file. Please refer to
589
     * {@see render()} on how to specify this parameter.
590
     *
591
     * @throws RuntimeException If a relative view name is given while there is no active context to determine the
592
     * corresponding view file.
593
     *
594
     * @return string The view file path. Note that the file may not exist.
595
     */
596 58
    private function findTemplateFile(string $view): string
597
    {
598 58
        if ($view !== '' && $view[0] === '/') {
599
            // path relative to basePath e.g. "/layouts/main"
600 54
            $file = $this->basePath . '/' . ltrim($view, '/');
601 7
        } elseif (($currentViewFile = $this->getRequestedViewFile()) !== null) {
602
            // path relative to currently rendered view
603 3
            $file = dirname($currentViewFile) . '/' . $view;
604 5
        } elseif ($this->context instanceof ViewContextInterface) {
605
            // path provided by context
606 4
            $file = $this->context->getViewPath() . '/' . $view;
607
        } else {
608 1
            throw new RuntimeException("Unable to resolve view file for view \"$view\": no active view context.");
609
        }
610
611 57
        if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
612 47
            return $file;
613
        }
614
615 10
        $path = $file . '.' . $this->defaultExtension;
616
617 10
        if ($this->defaultExtension !== 'php' && !is_file($path)) {
618 1
            $path = $file . '.php';
619
        }
620
621 10
        return $path;
622
    }
623
624
    /**
625
     * @return string|null The requested view currently being rendered. `null` if no view file is being rendered.
626
     */
627 7
    private function getRequestedViewFile(): ?string
628
    {
629
        /** @psalm-suppress InvalidArrayOffset */
630 7
        return empty($this->viewFiles) ? null : end($this->viewFiles)['requested'];
631
    }
632
}
633