Passed
Push — master ( 016c11...abad67 )
by Alexander
14:07 queued 06:23
created

BaseView::removeParameter()   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
c 0
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
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_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 $parameters Parameters that are common for all view templates.
210
     *
211
     * @psalm-param array<string, mixed> $parameters
212
     *
213
     * @return static
214
     *
215
     * @see setParameter()
216
     */
217 3
    public function setParameters(array $parameters): self
218
    {
219
        /** @var mixed $value */
220 3
        foreach ($parameters as $id => $value) {
221 1
            $this->setParameter($id, $value);
222
        }
223 3
        return $this;
224
    }
225
226
    /**
227
     * Sets a common parameter that is accessible in all view templates.
228
     *
229
     * @param string $id The unique identifier of the parameter.
230
     * @param mixed $value The value of the parameter.
231
     *
232
     * @return static
233
     */
234 5
    public function setParameter(string $id, $value): self
235
    {
236 5
        $this->parameters[$id] = $value;
237 5
        return $this;
238
    }
239
240
    /**
241
     * Removes a common parameter.
242
     *
243
     * @param string $id The unique identifier of the parameter.
244
     */
245 1
    public function removeParameter(string $id): void
246
    {
247 1
        unset($this->parameters[$id]);
248 1
    }
249
250
    /**
251
     * Gets a common parameter value by ID.
252
     *
253
     * @param string $id The unique identifier of the parameter.
254
     * @param mixed $default The default value to be returned if the specified parameter does not exist.
255
     *
256
     * @throws InvalidArgumentException If specified parameter does not exist and not passed default value.
257
     *
258
     * @return mixed The value of the parameter.
259
     */
260 2
    public function getParameter(string $id)
261
    {
262 2
        if (isset($this->parameters[$id])) {
263 1
            return $this->parameters[$id];
264
        }
265
266 2
        $args = func_get_args();
267 2
        if (array_key_exists(1, $args)) {
268 1
            return $args[1];
269
        }
270
271 1
        throw new InvalidArgumentException('Common parameter: "' . $id . '" not found.');
272
    }
273
274
    /**
275
     * Checks the existence of a common parameter by ID.
276
     *
277
     * @param string $id The unique identifier of the parameter.
278
     *
279
     * @return bool Whether a custom parameter that is common for all view templates exists.
280
     */
281 1
    public function hasParameter(string $id): bool
282
    {
283 1
        return isset($this->parameters[$id]);
284
    }
285
286
    /**
287
     * Sets a content block.
288
     *
289
     * @param string $id The unique identifier of the block.
290
     * @param string $content The content of the block.
291
     *
292
     * @return static
293
     */
294 3
    public function setBlock(string $id, string $content): self
295
    {
296 3
        $this->blocks[$id] = $content;
297 3
        return $this;
298
    }
299
300
    /**
301
     * Removes a content block.
302
     *
303
     * @param string $id The unique identifier of the block.
304
     */
305 1
    public function removeBlock(string $id): void
306
    {
307 1
        unset($this->blocks[$id]);
308 1
    }
309
310
    /**
311
     * Gets content of the block by ID.
312
     *
313
     * @param string $id The unique identifier of the block.
314
     *
315
     * @return string The content of the block.
316
     */
317 1
    public function getBlock(string $id): string
318
    {
319 1
        if (isset($this->blocks[$id])) {
320 1
            return $this->blocks[$id];
321
        }
322
323 1
        throw new InvalidArgumentException('Block: "' . $id . '" not found.');
324
    }
325
326
    /**
327
     * Checks the existence of a content block by ID.
328
     *
329
     * @param string $id The unique identifier of the block.
330
     *
331
     * @return bool Whether a content block exists.
332
     */
333 1
    public function hasBlock(string $id): bool
334
    {
335 1
        return isset($this->blocks[$id]);
336
    }
337
338
    /**
339
     * Gets the view file currently being rendered.
340
     *
341
     * @return string|null The view file currently being rendered. `null` if no view file is being rendered.
342
     */
343 1
    public function getViewFile(): ?string
344
    {
345
        /** @psalm-suppress InvalidArrayOffset */
346 1
        return empty($this->viewFiles) ? null : end($this->viewFiles)['resolved'];
347
    }
348
349
    /**
350
     * Gets the placeholder signature.
351
     *
352
     * @return string The placeholder signature.
353
     */
354 47
    final public function getPlaceholderSignature(): string
355
    {
356 47
        return $this->placeholderSignature;
357
    }
358
359
    /**
360
     * Sets a salt for the placeholder signature {@see getPlaceholderSignature()}.
361
     *
362
     * @param string $salt The placeholder salt.
363
     *
364
     * @return static
365
     */
366 102
    final public function setPlaceholderSalt(string $salt): self
367
    {
368 102
        $this->placeholderSignature = dechex(crc32($salt));
369 102
        return $this;
370
    }
371
372
    /**
373
     * Renders a view.
374
     *
375
     * The view to be rendered can be specified in one of the following formats:
376
     *
377
     * - The name of the view starting with a slash to join the base path {@see getBasePath()} (e.g. "/site/index").
378
     * - The name of the view without the starting slash (e.g. "site/index"). The corresponding view file will be
379
     *   looked for under the {@see ViewContextInterface::getViewPath()} of the context set via {@see withContext()}.
380
     *   If the context instance was not set {@see withContext()}, it will be looked for under the directory containing
381
     *   the view currently being rendered (i.e., this happens when rendering a view within another view).
382
     *
383
     * @param string $view The view name.
384
     * @param array $parameters The parameters (name-value pairs) that will be extracted and made available in the view
385
     * file.
386
     *
387
     * @throws RuntimeException If the view cannot be resolved.
388
     * @throws ViewNotFoundException If the view file does not exist.
389
     * @throws Throwable
390
     *
391
     * {@see renderFile()}
392
     *
393
     * @return string The rendering result.
394
     */
395 49
    public function render(string $view, array $parameters = []): string
396
    {
397 49
        $viewFile = $this->findTemplateFile($view);
398
399 48
        return $this->renderFile($viewFile, $parameters);
400
    }
401
402
    /**
403
     * Renders a view file.
404
     *
405
     * If the theme was set {@see withTheme()}, it will try to render the themed version of the view file
406
     * as long as it is available.
407
     *
408
     * If the renderer was set {@see withRenderers()}, the method will use it to render the view file. Otherwise,
409
     * it will simply include the view file as a normal PHP file, capture its output and return it as a string.
410
     *
411
     * @param string $viewFile The full absolute path of the view file.
412
     * @param array $parameters The parameters (name-value pairs) that will be extracted and made available in the view
413
     * file.
414
     *
415
     * @throws Throwable
416
     * @throws ViewNotFoundException If the view file does not exist
417
     *
418
     * @return string The rendering result.
419
     */
420 52
    public function renderFile(string $viewFile, array $parameters = []): string
421
    {
422 52
        $parameters = array_merge($this->parameters, $parameters);
423
424
        // TODO: these two match now
425 52
        $requestedFile = $viewFile;
426
427 52
        if ($this->theme !== null) {
428 1
            $viewFile = $this->theme->applyTo($viewFile);
429
        }
430
431 52
        if (is_file($viewFile)) {
432 51
            $viewFile = $this->localize($viewFile);
433
        } else {
434 1
            throw new ViewNotFoundException("The view file \"$viewFile\" does not exist.");
435
        }
436
437 51
        $output = '';
438 51
        $this->viewFiles[] = [
439 51
            'resolved' => $viewFile,
440 51
            'requested' => $requestedFile,
441
        ];
442
443 51
        if ($this->beforeRender($viewFile, $parameters)) {
444 51
            $ext = pathinfo($viewFile, PATHINFO_EXTENSION);
445 51
            $renderer = $this->renderers[$ext] ?? new PhpTemplateRenderer();
446 51
            $output = $renderer->render($this, $viewFile, $parameters);
447 51
            $output = $this->afterRender($viewFile, $parameters, $output);
448
        }
449
450 51
        array_pop($this->viewFiles);
451
452 51
        return $output;
453
    }
454
455
    /**
456
     * Returns the localized version of a specified file.
457
     *
458
     * The searching is based on the specified language code. In particular, a file with the same name will be looked
459
     * for under the subdirectory whose name is the same as the language code. For example, given the file
460
     * "path/to/view.php" and language code "zh-CN", the localized file will be looked for as "path/to/zh-CN/view.php".
461
     * If the file is not found, it will try a fallback with just a language code that is "zh"
462
     * i.e. "path/to/zh/view.php".
463
     * If it is not found as well the original file will be returned.
464
     *
465
     * If the target and the source language codes are the same, the original file will be returned.
466
     *
467
     * @param string $file The original file
468
     * @param string|null $language The target language that the file should be localized to.
469
     * @param string|null $sourceLanguage The language that the original file is in.
470
     *
471
     * @return string The matching localized file, or the original file if the localized version is not found.
472
     * If the target and the source language codes are the same, the original file will be returned.
473
     */
474 53
    public function localize(string $file, ?string $language = null, ?string $sourceLanguage = null): string
475
    {
476 53
        $language = $language ?? $this->language;
477 53
        $sourceLanguage = $sourceLanguage ?? $this->sourceLanguage;
478
479 53
        if ($language === $sourceLanguage) {
480 53
            return $file;
481
        }
482
483 2
        $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
484
485 2
        if (is_file($desiredFile)) {
486 2
            return $desiredFile;
487
        }
488
489 1
        $language = substr($language, 0, 2);
490
491 1
        if ($language === $sourceLanguage) {
492 1
            return $file;
493
        }
494
495 1
        $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
496 1
        return is_file($desiredFile) ? $desiredFile : $file;
497
    }
498
499
    /**
500
     * Clears the data for working with the event loop.
501
     */
502 46
    public function clear(): void
503
    {
504 46
        $this->viewFiles = [];
505 46
    }
506
507
    /**
508
     * Creates an event that occurs before rendering.
509
     *
510
     * @param string $viewFile The view file to be rendered.
511
     * @param array $parameters The parameter array passed to the {@see renderFile()} method.
512
     *
513
     * @return StoppableEventInterface The stoppable event instance.
514
     */
515
    abstract protected function createBeforeRenderEvent(string $viewFile, array $parameters): StoppableEventInterface;
516
517
    /**
518
     * Creates an event that occurs after rendering.
519
     *
520
     * @param string $viewFile The view file being rendered.
521
     * @param array $parameters The parameter array passed to the {@see renderFile()} method.
522
     * @param string $result The rendering result of the view file.
523
     *
524
     * @return AfterRenderEventInterface The event instance.
525
     */
526
    abstract protected function createAfterRenderEvent(
527
        string $viewFile,
528
        array $parameters,
529
        string $result
530
    ): AfterRenderEventInterface;
531
532
    /**
533
     * This method is invoked right before {@see renderFile()} renders a view file.
534
     *
535
     * The default implementations will trigger the {@see \Yiisoft\View\Event\View\BeforeRender}
536
     * or {@see \Yiisoft\View\Event\WebView\BeforeRender} event. If you override this method,
537
     * make sure you call the parent implementation first.
538
     *
539
     * @param string $viewFile The view file to be rendered.
540
     * @param array $parameters The parameter array passed to the {@see renderFile()} method.
541
     *
542
     * @return bool Whether to continue rendering the view file.
543
     */
544 51
    protected function beforeRender(string $viewFile, array $parameters): bool
545
    {
546 51
        $event = $this->createBeforeRenderEvent($viewFile, $parameters);
547 51
        $event = $this->eventDispatcher->dispatch($event);
548
        /** @var StoppableEventInterface $event */
549 51
        return !$event->isPropagationStopped();
550
    }
551
552
    /**
553
     * This method is invoked right after {@see renderFile()} renders a view file.
554
     *
555
     * The default implementations will trigger the {@see \Yiisoft\View\Event\View\AfterRender}
556
     * or {@see \Yiisoft\View\Event\WebView\AfterRender} event. If you override this method,
557
     * make sure you call the parent implementation first.
558
     *
559
     * @param string $viewFile The view file being rendered.
560
     * @param array $parameters The parameter array passed to the {@see renderFile()} method.
561
     * @param string $result The rendering result of the view file.
562
     *
563
     * @return string Updated output. It will be passed to {@see renderFile()} and returned.
564
     */
565 51
    protected function afterRender(string $viewFile, array $parameters, string $result): string
566
    {
567 51
        $event = $this->createAfterRenderEvent($viewFile, $parameters, $result);
568
569
        /** @var AfterRenderEventInterface $event */
570 51
        $event = $this->eventDispatcher->dispatch($event);
571
572 51
        return $event->getResult();
573
    }
574
575
    /**
576
     * Finds the view file based on the given view name.
577
     *
578
     * @param string $view The view name of the view file. Please refer to
579
     * {@see render()} on how to specify this parameter.
580
     *
581
     * @throws RuntimeException If a relative view name is given while there is no active context to determine the
582
     * corresponding view file.
583
     *
584
     * @return string The view file path. Note that the file may not exist.
585
     */
586 51
    protected function findTemplateFile(string $view): string
587
    {
588 51
        if ($view !== '' && $view[0] === '/') {
589
            // path relative to basePath e.g. "/layouts/main"
590 48
            $file = $this->basePath . '/' . ltrim($view, '/');
591 4
        } elseif (($currentViewFile = $this->getRequestedViewFile()) !== null) {
592
            // path relative to currently rendered view
593 2
            $file = dirname($currentViewFile) . '/' . $view;
594 3
        } elseif ($this->context instanceof ViewContextInterface) {
595
            // path provided by context
596 2
            $file = $this->context->getViewPath() . '/' . $view;
597
        } else {
598 1
            throw new RuntimeException("Unable to resolve view file for view \"$view\": no active view context.");
599
        }
600
601 50
        if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
602 45
            return $file;
603
        }
604
605 5
        $path = $file . '.' . $this->defaultExtension;
606
607 5
        if ($this->defaultExtension !== 'php' && !is_file($path)) {
608 1
            $path = $file . '.php';
609
        }
610
611 5
        return $path;
612
    }
613
614
    /**
615
     * @return string|null The requested view currently being rendered. `null` if no view file is being rendered.
616
     */
617 4
    private function getRequestedViewFile(): ?string
618
    {
619
        /** @psalm-suppress InvalidArrayOffset */
620 4
        return empty($this->viewFiles) ? null : end($this->viewFiles)['requested'];
621
    }
622
}
623