Passed
Push — master ( 0e2863...12b99e )
by Alexander
02:19
created

ViewTrait::setLanguage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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

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