Passed
Pull Request — master (#184)
by Sergei
02:36 queued 14s
created

BaseView::getParameter()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

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