Passed
Pull Request — master (#142)
by Sergei
02:15
created

View::withStringRenderer()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 5
ccs 4
cts 4
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 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
use Yiisoft\View\StringRenderer\PhpEvalStringRenderer;
17
use Yiisoft\View\StringRenderer\StringRendererInterface;
18
19
/**
20
 * View represents a view object in the MVC pattern.
21
 *
22
 * View provides a set of methods (e.g. {@see View::render()}) for rendering purpose.
23
 *
24
 * For more details and usage information on View, see the [guide article on views](guide:structure-views).
25
 */
26
class View implements DynamicContentAwareInterface
27
{
28
    /**
29
     * @var string view path
30
     */
31
    private string $basePath;
32
33
    /**
34
     * @var array a list of named output blocks. The keys are the block names and the values are the corresponding block
35
     * content. You can call {@see beginBlock()} and {@see endBlock()} to capture small fragments of a view.
36
     * They can be later accessed somewhere else through this property.
37
     */
38
    private array $blocks;
39
40
    /**
41
     * @var ViewContextInterface|null the context under which the {@see renderFile()} method is being invoked.
42
     */
43
    private ?ViewContextInterface $context = null;
44
45
    /**
46
     * @var string the default view file extension. This will be appended to view file names if they don't have file
47
     * extensions.
48
     */
49
    private string $defaultExtension = 'php';
50
51
    /**
52
     * @var array custom parameters that are shared among view templates.
53
     */
54
    private array $defaultParameters = [];
55
56
    /**
57
     * @var EventDispatcherInterface
58
     */
59
    protected EventDispatcherInterface $eventDispatcher;
60
61
    /**
62
     * @var array a list of available renderers indexed by their corresponding supported file extensions. Each renderer
63
     * may be a view renderer object or the configuration for creating the renderer object. For example, the
64
     * following configuration enables the Twig view renderer:
65
     *
66
     * ```php
67
     * [
68
     *     'twig' => ['class' => \Yiisoft\Yii\Twig\ViewRenderer::class],
69
     * ]
70
     * ```
71
     *
72
     * If no renderer is available for the given view file, the view file will be treated as a normal PHP and rendered
73
     * via PhpTemplateRenderer.
74
     */
75
    protected array $renderers = [];
76
77
    private ?StringRendererInterface $stringRenderer = null;
78
79
    /**
80
     * @var Theme|null The theme object.
81
     */
82
    protected ?Theme $theme = null;
83
84
    /**
85
     * @var DynamicContentAwareInterface[] a list of currently active dynamic content class instances.
86
     */
87
    private array $cacheStack = [];
88
89
    /**
90
     * @var array a list of placeholders for embedding dynamic contents.
91
     */
92
    private array $dynamicPlaceholders = [];
93
94
    /**
95
     * @var string
96
     */
97
    private string $language = 'en';
98
99
    /**
100
     * @var LoggerInterface
101
     */
102
    private LoggerInterface $logger;
103
104
    /**
105
     * @var string
106
     */
107
    private string $sourceLanguage = 'en';
108
109
    /**
110
     * @var Locale|null source locale used to find localized view file.
111
     */
112
    private ?Locale $sourceLocale = null;
113
114
    private string $placeholderSignature;
115
116
    /**
117
     * @var array the view files currently being rendered. There may be multiple view files being
118
     * rendered at a moment because one view may be rendered within another.
119
     */
120
    private array $viewFiles = [];
121
122 28
    public function __construct(string $basePath, EventDispatcherInterface $eventDispatcher, LoggerInterface $logger)
123
    {
124 28
        $this->basePath = $basePath;
125 28
        $this->eventDispatcher = $eventDispatcher;
126 28
        $this->logger = $logger;
127 28
        $this->setPlaceholderSalt(__DIR__);
128 28
    }
129
130
    /**
131
     * @return static
132
     */
133 1
    public function withTheme(Theme $theme): self
134
    {
135 1
        $new = clone $this;
136 1
        $new->theme = $theme;
137 1
        return $new;
138
    }
139
140 28
    public function setPlaceholderSalt(string $salt): void
141
    {
142 28
        $this->placeholderSignature = dechex(crc32($salt));
143 28
    }
144
145 12
    public function getPlaceholderSignature(): string
146
    {
147 12
        return $this->placeholderSignature;
148
    }
149
150
    public function getBasePath(): string
151
    {
152
        return $this->basePath;
153
    }
154
155
    public function withRenderers(array $renderers): self
156
    {
157
        $new = clone $this;
158
        $new->renderers = $renderers;
159
        return $new;
160
    }
161
162 1
    public function withStringRenderer(?StringRendererInterface $renderer): self
163
    {
164 1
        $new = clone $this;
165 1
        $new->stringRenderer = $renderer;
166 1
        return $new;
167
    }
168
169
    public function withSourceLanguage(string $language): self
170
    {
171
        $new = clone $this;
172
        $new->sourceLanguage = $language;
173
        return $new;
174
    }
175
176
    public function withLanguage(string $language): self
177
    {
178
        $new = clone $this;
179
        $new->language = $language;
180
        return $new;
181
    }
182
183 1
    public function withContext(ViewContextInterface $context): self
184
    {
185 1
        $new = clone $this;
186 1
        $new->context = $context;
187 1
        return $new;
188
    }
189
190
    public function getDefaultExtension(): string
191
    {
192
        return $this->defaultExtension;
193
    }
194
195
    public function withDefaultExtension(string $defaultExtension): self
196
    {
197
        $new = clone $this;
198
        $new->defaultExtension = $defaultExtension;
199
        return $new;
200
    }
201
202
    public function getDefaultParameters(): array
203
    {
204
        return $this->defaultParameters;
205
    }
206
207 2
    public function withDefaultParameters(array $defaultParameters): self
208
    {
209 2
        $new = clone $this;
210 2
        $new->defaultParameters = $defaultParameters;
211 2
        return $new;
212
    }
213
214
    /**
215
     * {@see blocks}
216
     *
217
     * @param string $id
218
     * @param string $value
219
     */
220
    public function setBlock(string $id, string $value): void
221
    {
222
        $this->blocks[$id] = $value;
223
    }
224
225
    /**
226
     * {@see blocks}
227
     *
228
     * @param string $id
229
     */
230
    public function removeBlock(string $id): void
231
    {
232
        unset($this->blocks[$id]);
233
    }
234
235
    /**
236
     * {@see blocks}
237
     *
238
     * @param string $id
239
     *
240
     * @return string
241
     */
242
    public function getBlock(string $id): string
243
    {
244
        if (isset($this->blocks[$id])) {
245
            return $this->blocks[$id];
246
        }
247
248
        throw new \InvalidArgumentException('Block: "' . $id . '" not found.');
249
    }
250
251
    /**
252
     * {@see blocks}
253
     *
254
     * @param string $id
255
     *
256
     * @return bool
257
     */
258
    public function hasBlock(string $id): bool
259
    {
260
        return isset($this->blocks[$id]);
261
    }
262
263
    /**
264
     * Renders a view.
265
     *
266
     * The view to be rendered can be specified in one of the following formats:
267
     *
268
     * - [path alias](guide:concept-aliases) (e.g. "@app/views/site/index");
269
     * - absolute path within application (e.g. "//site/index"): the view name starts with double slashes. The actual
270
     *   view file will be looked for under the [[Application::viewPath|view path]] of the application.
271
     * - absolute path within current module (e.g. "/site/index"): the view name starts with a single slash. The actual
272
     *   view file will be looked for under the [[Module::viewPath|view path]] of the [[Controller::module|current module]].
273
     * - relative view (e.g. "index"): the view name does not start with `@` or `/`. The corresponding view file will be
274
     *   looked for under the {@see ViewContextInterface::getViewPath()} of the {@see View::$context}.
275
     *   If {@see View::$context} is not set, it will be looked for under the directory containing the view currently
276
     *   being rendered (i.e., this happens when rendering a view within another view).
277
     *
278
     * @param string $view the view name.
279
     * @param array $parameters the parameters (name-value pairs) that will be extracted and made available in the view
280
     * file.
281
     *
282
     * @throws RuntimeException if the view cannot be resolved.
283
     * @throws ViewNotFoundException if the view file does not exist.
284
     * @throws \Throwable
285
     *
286
     * {@see renderFile()}
287
     *
288
     * @return string the rendering result
289
     */
290 5
    public function render(string $view, array $parameters = []): string
291
    {
292 5
        $viewFile = $this->findTemplateFile($view);
293
294 5
        return $this->renderFile($viewFile, $parameters);
295
    }
296
297
    /**
298
     * Finds the view file based on the given view name.
299
     *
300
     * @param string $view the view name or the [path alias](guide:concept-aliases) of the view file. Please refer to
301
     * {@see render()} on how to specify this parameter.
302
     *
303
     * @throws RuntimeException if a relative view name is given while there is no active context to determine the
304
     * corresponding view file.
305
     *
306
     * @return string the view file path. Note that the file may not exist.
307
     */
308 7
    protected function findTemplateFile(string $view): string
309
    {
310 7
        if (strncmp($view, '//', 2) === 0) {
311
            // path relative to basePath e.g. "//layouts/main"
312 6
            $file = $this->basePath . '/' . ltrim($view, '/');
313 2
        } elseif (($currentViewFile = $this->getRequestedViewFile()) !== null) {
314
            // path relative to currently rendered view
315 2
            $file = dirname($currentViewFile) . '/' . $view;
316 1
        } elseif ($this->context instanceof ViewContextInterface) {
317
            // path provided by context
318 1
            $file = $this->context->getViewPath() . '/' . $view;
319
        } else {
320
            throw new RuntimeException("Unable to resolve view file for view '$view': no active view context.");
321
        }
322
323 7
        if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
324 3
            return $file;
325
        }
326
327 4
        $path = $file . '.' . $this->defaultExtension;
328
329 4
        if ($this->defaultExtension !== 'php' && !is_file($path)) {
330
            $path = $file . '.php';
331
        }
332
333 4
        return $path;
334
    }
335
336
    /**
337
     * Renders a view file.
338
     *
339
     * If {@see theme} is enabled (not null), it will try to render the themed version of the view file as long as it
340
     * is available.
341
     *
342
     * If {@see renderers} is enabled (not null), the method will use it to render the view file. Otherwise,
343
     * it will simply include the view file as a normal PHP file, capture its output and
344
     * return it as a string.
345
     *
346
     * @param string $viewFile the view file. This can be either an absolute file path or an alias of it.
347
     * @param array $parameters the parameters (name-value pairs) that will be extracted and made available in the view
348
     * file.
349
     *
350
     * @throws \Throwable
351
     * @throws ViewNotFoundException if the view file does not exist
352
     *
353
     * @return string the rendering result
354
     */
355 16
    public function renderFile(string $viewFile, array $parameters = []): string
356
    {
357 16
        $parameters = array_merge($this->defaultParameters, $parameters);
358
359
        // TODO: these two match now
360 16
        $requestedFile = $viewFile;
361
362 16
        if ($this->theme !== null) {
363 1
            $viewFile = $this->theme->applyTo($viewFile);
364
        }
365
366 16
        if (is_file($viewFile)) {
367 16
            $viewFile = $this->localize($viewFile);
368
        } else {
369
            throw new ViewNotFoundException("The view file does not exist: $viewFile");
370
        }
371
372 16
        $output = '';
373 16
        $this->viewFiles[] = [
374 16
            'resolved' => $viewFile,
375 16
            'requested' => $requestedFile,
376
        ];
377
378 16
        if ($this->beforeRender($viewFile, $parameters)) {
379 16
            $this->logger->debug("Rendering view file: $viewFile");
380 16
            $ext = pathinfo($viewFile, PATHINFO_EXTENSION);
381 16
            $renderer = $this->renderers[$ext] ?? new PhpTemplateRenderer();
382 16
            $output = $renderer->render($this, $viewFile, $parameters);
383
384 16
            $output = $this->afterRender($viewFile, $parameters, $output);
385
        }
386
387 16
        array_pop($this->viewFiles);
388
389 16
        return $output;
390
    }
391
392 1
    public function renderString(string $viewString, array $parameters = []): string
393
    {
394 1
        $parameters = array_merge($this->defaultParameters, $parameters);
395
396 1
        $output = '';
397
398 1
        if ($this->beforeRender(null, $parameters)) {
399 1
            $this->logger->debug('Rendering view string.');
400 1
            $renderer = $this->stringRenderer ?? new PhpEvalStringRenderer();
401 1
            $output = $renderer->render($this, $viewString, $parameters);
402 1
            $output = $this->afterRender(null, $parameters, $output);
403
        }
404
405 1
        return $output;
406
    }
407
408
    /**
409
     * Returns the localized version of a specified file.
410
     *
411
     * The searching is based on the specified language code. In particular, a file with the same name will be looked
412
     * for under the subdirectory whose name is the same as the language code. For example, given the file
413
     * "path/to/view.php" and language code "zh-CN", the localized file will be looked for as path/to/zh-CN/view.php".
414
     * 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".
415
     * If it is not found as well the original file will be returned.
416
     *
417
     * If the target and the source language codes are the same, the original file will be returned.
418
     *
419
     * @param string $file the original file
420
     * @param string|null $language the target language that the file should be localized to.
421
     * @param string|null $sourceLanguage the language that the original file is in.
422
     *
423
     * @return string the matching localized file, or the original file if the localized version is not found.
424
     * If the target and the source language codes are the same, the original file will be returned.
425
     */
426 17
    public function localize(string $file, ?string $language = null, ?string $sourceLanguage = null): string
427
    {
428 17
        $language = $language ?? $this->language;
429 17
        $sourceLanguage = $sourceLanguage ?? $this->sourceLanguage;
430
431 17
        if ($language === $sourceLanguage) {
432 17
            return $file;
433
        }
434 1
        $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
435 1
        if (is_file($desiredFile)) {
436 1
            return $desiredFile;
437
        }
438
439
        $language = substr($language, 0, 2);
440
        if ($language === $sourceLanguage) {
441
            return $file;
442
        }
443
        $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
444
445
        return is_file($desiredFile) ? $desiredFile : $file;
446
    }
447
448
    /**
449
     * @return string|null The view file currently being rendered. `null` if no view file is being rendered.
450
     */
451 11
    public function getViewFile(): ?string
452
    {
453 11
        return empty($this->viewFiles) ? null : end($this->viewFiles)['resolved'];
454
    }
455
456
    /**
457
     * @return string|null The requested view currently being rendered. `null` if no view file is being rendered.
458
     */
459 2
    protected function getRequestedViewFile(): ?string
460
    {
461 2
        return empty($this->viewFiles) ? null : end($this->viewFiles)['requested'];
462
    }
463
464
    /**
465
     * This method is invoked right before {@see renderFile()} renders a view file.
466
     *
467
     * The default implementation will trigger the {@see BeforeRender()} event. If you override this method, make sure
468
     * you call the parent implementation first.
469
     *
470
     * @param string|null $viewFile the view file to be rendered.
471
     * @param array $parameters the parameter array passed to the {@see render()} method.
472
     *
473
     * @return bool whether to continue rendering the view file.
474
     */
475 17
    public function beforeRender(?string $viewFile, array $parameters): bool
476
    {
477 17
        $event = new BeforeRender($viewFile, $parameters);
478 17
        $event = $this->eventDispatcher->dispatch($event);
479
480 17
        return !$event->isPropagationStopped();
481
    }
482
483
    /**
484
     * This method is invoked right after {@see renderFile()} renders a view file.
485
     *
486
     * The default implementation will trigger the {@see AfterRender} event. If you override this method, make sure you
487
     * call the parent implementation first.
488
     *
489
     * @param string $viewFile the view file being rendered.
490
     * @param array $parameters the parameter array passed to the {@see render()} method.
491
     * @param string $output the rendering result of the view file.
492
     *
493
     * @return string Updated output. It will be passed to {@see renderFile()} and returned.
494
     */
495 17
    public function afterRender(?string $viewFile, array $parameters, string $output): string
496
    {
497 17
        $event = new AfterRender($viewFile, $parameters, $output);
498 17
        $event = $this->eventDispatcher->dispatch($event);
499
500 17
        return $event->getResult();
501
    }
502
503
    /**
504
     * Renders dynamic content returned by the given PHP statements.
505
     *
506
     * This method is mainly used together with content caching (fragment caching and page caching) when some portions
507
     * of the content (called *dynamic content*) should not be cached. The dynamic content must be returned by some PHP
508
     * statements. You can optionally pass additional parameters that will be available as variables in the PHP
509
     * statement:.
510
     *
511
     * ```php
512
     * <?= $this->renderDynamic('return foo($myVar);', [
513
     *     'myVar' => $model->getMyComplexVar(),
514
     * ]) ?>
515
     * ```
516
     *
517
     * @param string $statements the PHP statements for generating the dynamic content.
518
     * @param array $parameters the parameters (name-value pairs) that will be extracted and made
519
     * available in the $statement context. The parameters will be stored in the cache and be reused
520
     * each time $statement is executed. You should make sure, that these are safely serializable.
521
     *
522
     * @return string the placeholder of the dynamic content, or the dynamic content if there is no active content
523
     *                cache currently.
524
     */
525
    public function renderDynamic(string $statements, array $parameters = []): string
526
    {
527
        if (!empty($parameters)) {
528
            $statements = 'extract(unserialize(\'' . str_replace(['\\', '\''], ['\\\\', '\\\''], serialize($parameters)) . '\'));' . $statements;
529
        }
530
531
        if (!empty($this->cacheStack)) {
532
            $n = count($this->dynamicPlaceholders);
533
            $placeholder = "<![CDATA[YII-DYNAMIC-$n-{$this->getPlaceholderSignature()}]]>";
534
            $this->addDynamicPlaceholder($placeholder, $statements);
535
536
            return $placeholder;
537
        }
538
539
        return $this->evaluateDynamicContent($statements);
540
    }
541
542
    /**
543
     * Get source locale.
544
     *
545
     * @return Locale
546
     */
547
    public function getSourceLocale(): Locale
548
    {
549
        if ($this->sourceLocale === null) {
550
            $this->sourceLocale = new Locale('en-US');
551
        }
552
553
        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...
554
    }
555
556
    /**
557
     * Set source locale.
558
     *
559
     * @param string $locale
560
     *
561
     * @return self
562
     */
563
    public function setSourceLocale(string $locale): self
564
    {
565
        $this->sourceLocale = new Locale($locale);
566
567
        return $this;
568
    }
569
570
    public function getDynamicPlaceholders(): array
571
    {
572
        return $this->dynamicPlaceholders;
573
    }
574
575
    public function setDynamicPlaceholders(array $placeholders): void
576
    {
577
        $this->dynamicPlaceholders = $placeholders;
578
    }
579
580
    public function addDynamicPlaceholder(string $name, string $statements): void
581
    {
582
        foreach ($this->cacheStack as $cache) {
583
            $cache->addDynamicPlaceholder($name, $statements);
584
        }
585
586
        $this->dynamicPlaceholders[$name] = $statements;
587
    }
588
589
    /**
590
     * Evaluates the given PHP statements.
591
     *
592
     * This method is mainly used internally to implement dynamic content feature.
593
     *
594
     * @param string $statements the PHP statements to be evaluated.
595
     *
596
     * @return mixed the return value of the PHP statements.
597
     */
598
    public function evaluateDynamicContent(string $statements)
599
    {
600
        return eval($statements);
0 ignored issues
show
introduced by
The use of eval() is discouraged.
Loading history...
601
    }
602
603
    /**
604
     * Returns a list of currently active dynamic content class instances.
605
     *
606
     * @return DynamicContentAwareInterface[] class instances supporting dynamic contents.
607
     */
608
    public function getDynamicContents(): array
609
    {
610
        return $this->cacheStack;
611
    }
612
613
    /**
614
     * Adds a class instance supporting dynamic contents to the end of a list of currently active dynamic content class
615
     * instances.
616
     *
617
     * @param DynamicContentAwareInterface $instance class instance supporting dynamic contents.
618
     */
619
    public function pushDynamicContent(DynamicContentAwareInterface $instance): void
620
    {
621
        $this->cacheStack[] = $instance;
622
    }
623
624
    /**
625
     * Removes a last class instance supporting dynamic contents from a list of currently active dynamic content class
626
     * instances.
627
     */
628
    public function popDynamicContent(): void
629
    {
630
        array_pop($this->cacheStack);
631
    }
632
633
    /**
634
     * Marks the beginning of a page.
635
     */
636 11
    public function beginPage(): void
637
    {
638 11
        ob_start();
639 11
        PHP_VERSION_ID >= 80000 ? ob_implicit_flush(false) : ob_implicit_flush(0);
640
641 11
        $this->eventDispatcher->dispatch(new PageBegin($this->getViewFile()));
642 11
    }
643
644
    /**
645
     * Marks the ending of a page.
646
     */
647
    public function endPage(): void
648
    {
649
        $this->eventDispatcher->dispatch(new PageEnd($this->getViewFile()));
650
        ob_end_flush();
651
    }
652
}
653