Passed
Pull Request — master (#137)
by
unknown
03:24
created

View::withLanguage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 5
ccs 0
cts 4
cp 0
rs 10
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\View;
6
7
use Psr\EventDispatcher\EventDispatcherInterface;
8
use Psr\Log\LoggerInterface;
9
use RuntimeException;
10
use Yiisoft\I18n\Locale;
11
use Yiisoft\View\Event\AfterRender;
12
use Yiisoft\View\Event\BeforeRender;
13
use Yiisoft\View\Event\PageBegin;
14
use Yiisoft\View\Event\PageEnd;
15
use Yiisoft\View\Exception\ViewNotFoundException;
16
17
/**
18
 * View represents a view object in the MVC pattern.
19
 *
20
 * View provides a set of methods (e.g. {@see View::render()}) for rendering purpose.
21
 *
22
 * For more details and usage information on View, see the [guide article on views](guide:structure-views).
23
 */
24
class View implements DynamicContentAwareInterface
25
{
26
    /**
27
     * @var string view path
28
     */
29
    private string $basePath;
30
31
    /**
32
     * @var array a list of named output blocks. The keys are the block names and the values are the corresponding block
33
     * content. You can call {@see beginBlock()} and {@see endBlock()} to capture small fragments of a view.
34
     * They can be later accessed somewhere else through this property.
35
     */
36
    private array $blocks;
37
38
    /**
39
     * @var ViewContextInterface|null the context under which the {@see renderFile()} method is being invoked.
40
     */
41
    private ?ViewContextInterface $context = null;
42
43
    /**
44
     * @var string the default view file extension. This will be appended to view file names if they don't have file
45
     * extensions.
46
     */
47
    private string $defaultExtension = 'php';
48
49
    /**
50
     * @var array custom parameters that are shared among view templates.
51
     */
52
    private array $defaultParameters = [];
53
54
    /**
55
     * @var EventDispatcherInterface
56
     */
57
    protected EventDispatcherInterface $eventDispatcher;
58
59
    /**
60
     * @var array a list of available renderers indexed by their corresponding supported file extensions. Each renderer
61
     * may be a view renderer object or the configuration for creating the renderer object. For example, the
62
     * following configuration enables the Twig view renderer:
63
     *
64
     * ```php
65
     * [
66
     *     'twig' => ['class' => \Yiisoft\Yii\Twig\ViewRenderer::class],
67
     * ]
68
     * ```
69
     *
70
     * If no renderer is available for the given view file, the view file will be treated as a normal PHP and rendered
71
     * via PhpTemplateRenderer.
72
     */
73
    protected array $renderers = [];
74
75
    /**
76
     * @var Theme|null The theme object.
77
     */
78
    protected ?Theme $theme = null;
79
80
    /**
81
     * @var DynamicContentAwareInterface[] a list of currently active dynamic content class instances.
82
     */
83
    private array $cacheStack = [];
84
85
    /**
86
     * @var array a list of placeholders for embedding dynamic contents.
87
     */
88
    private array $dynamicPlaceholders = [];
89
90
    /**
91
     * @var string
92
     */
93
    private string $language = 'en';
94
95
    /**
96
     * @var LoggerInterface
97
     */
98
    private LoggerInterface $logger;
99
100
    /**
101
     * @var string
102
     */
103
    private string $sourceLanguage = 'en';
104
105
    /**
106
     * @var Locale|null source locale used to find localized view file.
107
     */
108
    private ?Locale $sourceLocale = null;
109
110
    private string $placeholderSignature;
111
112
    /**
113
     * @var array the view files currently being rendered. There may be multiple view files being
114
     * rendered at a moment because one view may be rendered within another.
115
     */
116
    private array $viewFiles = [];
117
118 22
    public function __construct(string $basePath, EventDispatcherInterface $eventDispatcher, LoggerInterface $logger)
119
    {
120 22
        $this->basePath = $basePath;
121 22
        $this->eventDispatcher = $eventDispatcher;
122 22
        $this->logger = $logger;
123 22
        $this->setPlaceholderSalt(__DIR__);
124 22
    }
125
126
    /**
127
     * @return static
128
     */
129 1
    public function withTheme(Theme $theme): self
130
    {
131 1
        $new = clone $this;
132 1
        $new->theme = $theme;
133 1
        return $new;
134
    }
135
136 22
    public function setPlaceholderSalt(string $salt): void
137
    {
138 22
        $this->placeholderSignature = dechex(crc32($salt));
139 22
    }
140
141 8
    public function getPlaceholderSignature(): string
142
    {
143 8
        return $this->placeholderSignature;
144
    }
145
146
    public function getBasePath(): string
147
    {
148
        return $this->basePath;
149
    }
150
151
    public function withRenderers(array $renderers): self
152
    {
153
        $new = clone $this;
154
        $new->renderers = $renderers;
155
        return $new;
156
    }
157
158
    public function withSourceLanguage(string $language): self
159
    {
160
        $new = clone $this;
161
        $new->sourceLanguage = $language;
162
        return $new;
163
    }
164
165
    public function withLanguage(string $language): self
166
    {
167
        $new = clone $this;
168
        $new->language = $language;
169
        return $new;
170
    }
171
172 1
    public function withContext(ViewContextInterface $context): self
173
    {
174 1
        $new = clone $this;
175 1
        $new->context = $context;
176 1
        return $new;
177
    }
178
179
    public function getDefaultExtension(): string
180
    {
181
        return $this->defaultExtension;
182
    }
183
184
    public function withDefaultExtension(string $defaultExtension): self
185
    {
186
        $new = clone $this;
187
        $new->defaultExtension = $defaultExtension;
188
        return $new;
189
    }
190
191
    public function getDefaultParameters(): array
192
    {
193
        return $this->defaultParameters;
194
    }
195
196 2
    public function withDefaultParameters(array $defaultParameters): self
197
    {
198 2
        $new = clone $this;
199 2
        $new->defaultParameters = $defaultParameters;
200 2
        return $new;
201
    }
202
203
    /**
204
     * {@see blocks}
205
     *
206
     * @param string $id
207
     * @param string $value
208
     */
209
    public function setBlock(string $id, string $value): void
210
    {
211
        $this->blocks[$id] = $value;
212
    }
213
214
    /**
215
     * {@see blocks}
216
     *
217
     * @param string $id
218
     */
219
    public function removeBlock(string $id): void
220
    {
221
        unset($this->blocks[$id]);
222
    }
223
224
    /**
225
     * {@see blocks}
226
     *
227
     * @param string $id
228
     *
229
     * @return string
230
     */
231
    public function getBlock(string $id): string
232
    {
233
        if (isset($this->blocks[$id])) {
234
            return $this->blocks[$id];
235
        }
236
237
        throw new \InvalidArgumentException('Block: "' . $id . '" not found.');
238
    }
239
240
    /**
241
     * {@see blocks}
242
     *
243
     * @param string $id
244
     *
245
     * @return bool
246
     */
247
    public function hasBlock(string $id): bool
248
    {
249
        return isset($this->blocks[$id]);
250
    }
251
252
    /**
253
     * Renders a view.
254
     *
255
     * The view to be rendered can be specified in one of the following formats:
256
     *
257
     * - [path alias](guide:concept-aliases) (e.g. "@app/views/site/index");
258
     * - absolute path within application (e.g. "//site/index"): the view name starts with double slashes. The actual
259
     *   view file will be looked for under the [[Application::viewPath|view path]] of the application.
260
     * - absolute path within current module (e.g. "/site/index"): the view name starts with a single slash. The actual
261
     *   view file will be looked for under the [[Module::viewPath|view path]] of the [[Controller::module|current module]].
262
     * - relative view (e.g. "index"): the view name does not start with `@` or `/`. The corresponding view file will be
263
     *   looked for under the {@see ViewContextInterface::getViewPath()} of the {@see View::$context}.
264
     *   If {@see View::$context} is not set, it will be looked for under the directory containing the view currently
265
     *   being rendered (i.e., this happens when rendering a view within another view).
266
     *
267
     * @param string $view the view name.
268
     * @param array $parameters the parameters (name-value pairs) that will be extracted and made available in the view
269
     * file.
270
     *
271
     * @throws RuntimeException if the view cannot be resolved.
272
     * @throws ViewNotFoundException if the view file does not exist.
273
     * @throws \Throwable
274
     *
275
     * {@see renderFile()}
276
     *
277
     * @return string the rendering result
278
     */
279 5
    public function render(string $view, array $parameters = []): string
280
    {
281 5
        $viewFile = $this->findTemplateFile($view);
282
283 5
        return $this->renderFile($viewFile, $parameters);
284
    }
285
286
    /**
287
     * Finds the view file based on the given view name.
288
     *
289
     * @param string $view the view name or the [path alias](guide:concept-aliases) of the view file. Please refer to
290
     * {@see render()} on how to specify this parameter.
291
     *
292
     * @throws RuntimeException if a relative view name is given while there is no active context to determine the
293
     * corresponding view file.
294
     *
295
     * @return string the view file path. Note that the file may not exist.
296
     */
297 5
    protected function findTemplateFile(string $view): string
298
    {
299 5
        if (strncmp($view, '//', 2) === 0) {
300
            // path relative to basePath e.g. "//layouts/main"
301 4
            $file = $this->basePath . '/' . ltrim($view, '/');
302 2
        } elseif (($currentViewFile = $this->getRequestedViewFile()) !== false) {
303
            // path relative to currently rendered view
304 2
            $file = dirname($currentViewFile) . '/' . $view;
0 ignored issues
show
Bug introduced by
It seems like $currentViewFile can also be of type true; however, parameter $path of dirname() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

304
            $file = dirname(/** @scrutinizer ignore-type */ $currentViewFile) . '/' . $view;
Loading history...
305 1
        } elseif ($this->context instanceof ViewContextInterface) {
306
            // path provided by context
307 1
            $file = $this->context->getViewPath() . '/' . $view;
308
        } else {
309
            throw new RuntimeException("Unable to resolve view file for view '$view': no active view context.");
310
        }
311
312 5
        if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
313 1
            return $file;
314
        }
315
316 4
        $path = $file . '.' . $this->defaultExtension;
317
318 4
        if ($this->defaultExtension !== 'php' && !is_file($path)) {
319
            $path = $file . '.php';
320
        }
321
322 4
        return $path;
323
    }
324
325
    /**
326
     * Renders a view file.
327
     *
328
     * If {@see theme} is enabled (not null), it will try to render the themed version of the view file as long as it
329
     * is available.
330
     *
331
     * If {@see renderers} is enabled (not null), the method will use it to render the view file. Otherwise,
332
     * it will simply include the view file as a normal PHP file, capture its output and
333
     * return it as a string.
334
     *
335
     * @param string $viewFile the view file. This can be either an absolute file path or an alias of it.
336
     * @param array $parameters the parameters (name-value pairs) that will be extracted and made available in the view
337
     * file.
338
     *
339
     * @throws \Throwable
340
     * @throws ViewNotFoundException if the view file does not exist
341
     *
342
     * @return string the rendering result
343
     */
344 12
    public function renderFile(string $viewFile, array $parameters = []): string
345
    {
346 12
        $parameters = array_merge($this->defaultParameters, $parameters);
347
348
        // TODO: these two match now
349 12
        $requestedFile = $viewFile;
350
351 12
        if ($this->theme !== null) {
352 1
            $viewFile = $this->theme->applyTo($viewFile);
353
        }
354
355 12
        if (is_file($viewFile)) {
356 12
            $viewFile = $this->localize($viewFile);
357
        } else {
358
            throw new ViewNotFoundException("The view file does not exist: $viewFile");
359
        }
360
361 12
        $output = '';
362 12
        $this->viewFiles[] = [
363 12
            'resolved' => $viewFile,
364 12
            'requested' => $requestedFile,
365
        ];
366
367 12
        if ($this->beforeRender($viewFile, $parameters)) {
368 12
            $this->logger->debug("Rendering view file: $viewFile");
369 12
            $ext = pathinfo($viewFile, PATHINFO_EXTENSION);
370 12
            $renderer = $this->renderers[$ext] ?? new PhpTemplateRenderer();
371 12
            $output = $renderer->render($this, $viewFile, $parameters);
372
373 12
            $output = $this->afterRender($viewFile, $parameters, $output);
374
        }
375
376 12
        array_pop($this->viewFiles);
377
378 12
        return $output;
379
    }
380
381
    /**
382
     * Returns the localized version of a specified file.
383
     *
384
     * The searching is based on the specified language code. In particular, a file with the same name will be looked
385
     * for under the subdirectory whose name is the same as the language code. For example, given the file
386
     * "path/to/view.php" and language code "zh-CN", the localized file will be looked for as path/to/zh-CN/view.php".
387
     * If the file is not found, it will try a fallback with just a language code that is "zh" i.e. "path/to/zh/view.php".
388
     * If it is not found as well the original file will be returned.
389
     *
390
     * If the target and the source language codes are the same, the original file will be returned.
391
     *
392
     * @param string $file the original file
393
     * @param string|null $language the target language that the file should be localized to.
394
     * @param string|null $sourceLanguage the language that the original file is in.
395
     *
396
     * @return string the matching localized file, or the original file if the localized version is not found.
397
     * If the target and the source language codes are the same, the original file will be returned.
398
     */
399 13
    public function localize(string $file, ?string $language = null, ?string $sourceLanguage = null): string
400
    {
401 13
        $language = $language ?? $this->language;
402 13
        $sourceLanguage = $sourceLanguage ?? $this->sourceLanguage;
403
404 13
        if ($language === $sourceLanguage) {
405 13
            return $file;
406
        }
407 1
        $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
408 1
        if (is_file($desiredFile)) {
409 1
            return $desiredFile;
410
        }
411
412
        $language = substr($language, 0, 2);
413
        if ($language === $sourceLanguage) {
414
            return $file;
415
        }
416
        $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
417
418
        return is_file($desiredFile) ? $desiredFile : $file;
419
    }
420
421
    /**
422
     * @return bool|string the view file currently being rendered. False if no view file is being rendered.
423
     */
424 7
    public function getViewFile()
425
    {
426 7
        return empty($this->viewFiles) ? false : end($this->viewFiles)['resolved'];
427
    }
428
429
    /**
430
     * @return bool|string the requested view currently being rendered. False if no view file is being rendered.
431
     */
432 2
    protected function getRequestedViewFile()
433
    {
434 2
        return empty($this->viewFiles) ? false : end($this->viewFiles)['requested'];
435
    }
436
437
    /**
438
     * This method is invoked right before {@see renderFile()} renders a view file.
439
     *
440
     * The default implementation will trigger the {@see BeforeRender()} event. If you override this method, make sure
441
     * you call the parent implementation first.
442
     *
443
     * @param string $viewFile the view file to be rendered.
444
     * @param array $parameters the parameter array passed to the {@see render()} method.
445
     *
446
     * @return bool whether to continue rendering the view file.
447
     */
448 12
    public function beforeRender(string $viewFile, array $parameters): bool
449
    {
450 12
        $event = new BeforeRender($viewFile, $parameters);
451 12
        $event = $this->eventDispatcher->dispatch($event);
452
453 12
        return !$event->isPropagationStopped();
454
    }
455
456
    /**
457
     * This method is invoked right after {@see renderFile()} renders a view file.
458
     *
459
     * The default implementation will trigger the {@see AfterRender} event. If you override this method, make sure you
460
     * call the parent implementation first.
461
     *
462
     * @param string $viewFile the view file being rendered.
463
     * @param array $parameters the parameter array passed to the {@see render()} method.
464
     * @param string $output the rendering result of the view file.
465
     *
466
     * @return string Updated output. It will be passed to {@see renderFile()} and returned.
467
     */
468 12
    public function afterRender(string $viewFile, array $parameters, string $output): string
469
    {
470 12
        $event = new AfterRender($viewFile, $parameters, $output);
471 12
        $event = $this->eventDispatcher->dispatch($event);
472
473 12
        return $event->getResult();
474
    }
475
476
    /**
477
     * Renders dynamic content returned by the given PHP statements.
478
     *
479
     * This method is mainly used together with content caching (fragment caching and page caching) when some portions
480
     * of the content (called *dynamic content*) should not be cached. The dynamic content must be returned by some PHP
481
     * statements. You can optionally pass additional parameters that will be available as variables in the PHP
482
     * statement:.
483
     *
484
     * ```php
485
     * <?= $this->renderDynamic('return foo($myVar);', [
486
     *     'myVar' => $model->getMyComplexVar(),
487
     * ]) ?>
488
     * ```
489
     *
490
     * @param string $statements the PHP statements for generating the dynamic content.
491
     * @param array $parameters the parameters (name-value pairs) that will be extracted and made
492
     * available in the $statement context. The parameters will be stored in the cache and be reused
493
     * each time $statement is executed. You should make sure, that these are safely serializable.
494
     *
495
     * @return string the placeholder of the dynamic content, or the dynamic content if there is no active content
496
     *                cache currently.
497
     */
498
    public function renderDynamic(string $statements, array $parameters = []): string
499
    {
500
        if (!empty($parameters)) {
501
            $statements = 'extract(unserialize(\'' . str_replace(['\\', '\''], ['\\\\', '\\\''], serialize($parameters)) . '\'));' . $statements;
502
        }
503
504
        if (!empty($this->cacheStack)) {
505
            $n = count($this->dynamicPlaceholders);
506
            $placeholder = "<![CDATA[YII-DYNAMIC-$n-{$this->getPlaceholderSignature()}]]>";
507
            $this->addDynamicPlaceholder($placeholder, $statements);
508
509
            return $placeholder;
510
        }
511
512
        return $this->evaluateDynamicContent($statements);
513
    }
514
515
    /**
516
     * Get source locale.
517
     *
518
     * @return Locale
519
     */
520
    public function getSourceLocale(): Locale
521
    {
522
        if ($this->sourceLocale === null) {
523
            $this->sourceLocale = new Locale('en-US');
524
        }
525
526
        return $this->sourceLocale;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->sourceLocale could return the type null which is incompatible with the type-hinted return Yiisoft\I18n\Locale. Consider adding an additional type-check to rule them out.
Loading history...
527
    }
528
529
    /**
530
     * Set source locale.
531
     *
532
     * @param string $locale
533
     *
534
     * @return self
535
     */
536
    public function setSourceLocale(string $locale): self
537
    {
538
        $this->sourceLocale = new Locale($locale);
539
540
        return $this;
541
    }
542
543
    public function getDynamicPlaceholders(): array
544
    {
545
        return $this->dynamicPlaceholders;
546
    }
547
548
    public function setDynamicPlaceholders(array $placeholders): void
549
    {
550
        $this->dynamicPlaceholders = $placeholders;
551
    }
552
553
    public function addDynamicPlaceholder(string $name, string $statements): void
554
    {
555
        foreach ($this->cacheStack as $cache) {
556
            $cache->addDynamicPlaceholder($name, $statements);
557
        }
558
559
        $this->dynamicPlaceholders[$name] = $statements;
560
    }
561
562
    /**
563
     * Evaluates the given PHP statements.
564
     *
565
     * This method is mainly used internally to implement dynamic content feature.
566
     *
567
     * @param string $statements the PHP statements to be evaluated.
568
     *
569
     * @return mixed the return value of the PHP statements.
570
     */
571
    public function evaluateDynamicContent(string $statements)
572
    {
573
        return eval($statements);
0 ignored issues
show
introduced by
The use of eval() is discouraged.
Loading history...
574
    }
575
576
    /**
577
     * Returns a list of currently active dynamic content class instances.
578
     *
579
     * @return DynamicContentAwareInterface[] class instances supporting dynamic contents.
580
     */
581
    public function getDynamicContents(): array
582
    {
583
        return $this->cacheStack;
584
    }
585
586
    /**
587
     * Adds a class instance supporting dynamic contents to the end of a list of currently active dynamic content class
588
     * instances.
589
     *
590
     * @param DynamicContentAwareInterface $instance class instance supporting dynamic contents.
591
     */
592
    public function pushDynamicContent(DynamicContentAwareInterface $instance): void
593
    {
594
        $this->cacheStack[] = $instance;
595
    }
596
597
    /**
598
     * Removes a last class instance supporting dynamic contents from a list of currently active dynamic content class
599
     * instances.
600
     */
601
    public function popDynamicContent(): void
602
    {
603
        array_pop($this->cacheStack);
604
    }
605
606
    /**
607
     * Marks the beginning of a page.
608
     */
609 7
    public function beginPage(): void
610
    {
611 7
        ob_start();
612 7
        PHP_VERSION_ID >= 80000 ? ob_implicit_flush(false) : ob_implicit_flush(0);
613
614 7
        $this->eventDispatcher->dispatch(new PageBegin($this->getViewFile()));
0 ignored issues
show
Bug introduced by
It seems like $this->getViewFile() can also be of type boolean; however, parameter $file of Yiisoft\View\Event\PageBegin::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

614
        $this->eventDispatcher->dispatch(new PageBegin(/** @scrutinizer ignore-type */ $this->getViewFile()));
Loading history...
615 7
    }
616
617
    /**
618
     * Marks the ending of a page.
619
     */
620
    public function endPage(): void
621
    {
622
        $this->eventDispatcher->dispatch(new PageEnd($this->getViewFile()));
0 ignored issues
show
Bug introduced by
It seems like $this->getViewFile() can also be of type boolean; however, parameter $file of Yiisoft\View\Event\PageEnd::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

622
        $this->eventDispatcher->dispatch(new PageEnd(/** @scrutinizer ignore-type */ $this->getViewFile()));
Loading history...
623
        ob_end_flush();
624
    }
625
}
626