Passed
Pull Request — master (#75)
by Alexander
03:54
created

View::getPlaceholderSignature()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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

271
            $file = dirname(/** @scrutinizer ignore-type */ $currentViewFile) . '/' . $view;
Loading history...
272
        } else {
273
            throw new \RuntimeException("Unable to resolve view file for view '$view': no active view context.");
274
        }
275
276
        if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
277
            return $file;
278
        }
279
280
        $path = $file . '.' . $this->defaultExtension;
281
282
        if ($this->defaultExtension !== 'php' && !is_file($path)) {
283
            $path = $file . '.php';
284
        }
285
286
        return $path;
287
    }
288
289
    /**
290
     * Renders a view file.
291
     *
292
     * If {@see theme} is enabled (not null), it will try to render the themed version of the view file as long as it
293
     * is available.
294
     *
295
     * If {@see renderers|renderer} is enabled (not null), the method will use it to render the view file. Otherwise,
296
     * it will simply include the view file as a normal PHP file, capture its output and
297
     * return it as a string.
298
     *
299
     * @param string $viewFile the view file. This can be either an absolute file path or an alias of it.
300
     * @param array $parameters the parameters (name-value pairs) that will be extracted and made available in the view
301
     * file.
302
     * @param ViewContextInterface|null $context the context that the view should use for rendering the view. If null,
303
     * existing [[context]] will be used.
304
     *
305
     * @return string the rendering result
306
     * @throws \Throwable
307
     *
308
     * @throws ViewNotFoundException if the view file does not exist
309
     */
310
    public function renderFile(string $viewFile, array $parameters = [], ?ViewContextInterface $context = null): string
311
    {
312
        $parameters = array_merge($this->defaultParameters, $parameters);
313
314
        // TODO: these two match now
315
        $requestedFile = $viewFile;
316
317
        if (!empty($this->theme)) {
318
            $viewFile = $this->theme->applyTo($viewFile);
319
        }
320
321
        if (is_file($viewFile)) {
322
            $viewFile = $this->localize($viewFile);
323
        } else {
324
            throw new ViewNotFoundException("The view file does not exist: $viewFile");
325
        }
326
327
        $oldContext = $this->context;
328
        if ($context !== null) {
329
            $this->context = $context;
330
        }
331
        $output = '';
332
        $this->viewFiles[] = [
333
            'resolved' => $viewFile,
334
            'requested' => $requestedFile,
335
        ];
336
337
        if ($this->beforeRender($viewFile, $parameters)) {
338
            $this->logger->debug("Rendering view file: $viewFile");
339
            $ext = pathinfo($viewFile, PATHINFO_EXTENSION);
340
            $renderer = $this->renderers[$ext] ?? new PhpTemplateRenderer();
341
            $output = $renderer->render($this, $viewFile, $parameters);
342
343
            $output = $this->afterRender($viewFile, $parameters, $output);
344
        }
345
346
        array_pop($this->viewFiles);
347
        $this->context = $oldContext;
348
349
        return $output;
350
    }
351
352
    /**
353
     * Returns the localized version of a specified file.
354
     *
355
     * The searching is based on the specified language code. In particular, a file with the same name will be looked
356
     * for under the subdirectory whose name is the same as the language code. For example, given the file
357
     * "path/to/view.php" and language code "zh-CN", the localized file will be looked for as path/to/zh-CN/view.php".
358
     * 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".
359
     * If it is not found as well the original file will be returned.
360
     *
361
     * If the target and the source language codes are the same, the original file will be returned.
362
     *
363
     * @param string $file the original file
364
     * @param string|null $language the target language that the file should be localized to.
365
     * @param string|null $sourceLanguage the language that the original file is in.
366
     *
367
     * @return string the matching localized file, or the original file if the localized version is not found.
368
     * If the target and the source language codes are the same, the original file will be returned.
369
     */
370
    public function localize(string $file, ?string $language = null, ?string $sourceLanguage = null): string
371
    {
372
        $language = $language ?? $this->language;
373
        $sourceLanguage = $sourceLanguage ?? $this->sourceLanguage;
374
375
        if ($language === $sourceLanguage) {
376
            return $file;
377
        }
378
        $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
379
        if (is_file($desiredFile)) {
380
            return $desiredFile;
381
        }
382
383
        $language = substr($language, 0, 2);
384
        if ($language === $sourceLanguage) {
385
            return $file;
386
        }
387
        $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
388
389
        return is_file($desiredFile) ? $desiredFile : $file;
390
    }
391
392
    /**
393
     * @return string|bool the view file currently being rendered. False if no view file is being rendered.
394
     */
395
    public function getViewFile()
396
    {
397
        return empty($this->viewFiles) ? false : end($this->viewFiles)['resolved'];
398
    }
399
400
    /**
401
     * @return string|bool the requested view currently being rendered. False if no view file is being rendered.
402
     */
403
    protected function getRequestedViewFile()
404
    {
405
        return empty($this->viewFiles) ? false : end($this->viewFiles)['requested'];
406
    }
407
408
    /**
409
     * This method is invoked right before {@see renderFile()} renders a view file.
410
     *
411
     * The default implementation will trigger the {@see BeforeRender()} event. If you override this method, make sure
412
     * you call the parent implementation first.
413
     *
414
     * @param string $viewFile the view file to be rendered.
415
     * @param array $parameters the parameter array passed to the {@see render()} method.
416
     *
417
     * @return bool whether to continue rendering the view file.
418
     */
419
    public function beforeRender(string $viewFile, array $parameters): bool
420
    {
421
        $event = new BeforeRender($viewFile, $parameters);
422
        $event = $this->eventDispatcher->dispatch($event);
423
424
        return !$event->isPropagationStopped();
425
    }
426
427
    /**
428
     * This method is invoked right after {@see renderFile()} renders a view file.
429
     *
430
     * The default implementation will trigger the {@see AfterRender} event. If you override this method, make sure you
431
     * call the parent implementation first.
432
     *
433
     * @param string $viewFile the view file being rendered.
434
     * @param array $parameters the parameter array passed to the {@see render()} method.
435
     * @param string $output the rendering result of the view file. Updates to this parameter
436
     * will be passed back and returned by {@see renderFile()}.
437
     */
438
    public function afterRender(string $viewFile, array $parameters, &$output): string
439
    {
440
        $event = new AfterRender($viewFile, $parameters, $output);
441
        $event = $this->eventDispatcher->dispatch($event);
442
443
        return $event->getResult();
444
    }
445
446
    /**
447
     * Renders dynamic content returned by the given PHP statements.
448
     *
449
     * This method is mainly used together with content caching (fragment caching and page caching) when some portions
450
     * of the content (called *dynamic content*) should not be cached. The dynamic content must be returned by some PHP
451
     * statements. You can optionally pass additional parameters that will be available as variables in the PHP
452
     * statement:.
453
     *
454
     * ```php
455
     * <?= $this->renderDynamic('return foo($myVar);', [
456
     *     'myVar' => $model->getMyComplexVar(),
457
     * ]) ?>
458
     * ```
459
     *
460
     * @param string $statements the PHP statements for generating the dynamic content.
461
     * @param array $parameters the parameters (name-value pairs) that will be extracted and made
462
     * available in the $statement context. The parameters will be stored in the cache and be reused
463
     * each time $statement is executed. You should make sure, that these are safely serializable.
464
     *
465
     * @return string the placeholder of the dynamic content, or the dynamic content if there is no active content
466
     *                cache currently.
467
     */
468
    public function renderDynamic(string $statements, array $parameters = []): string
469
    {
470
        if (!empty($parameters)) {
471
            $statements = 'extract(unserialize(\'' . str_replace(['\\', '\''], ['\\\\', '\\\''], serialize($parameters)) . '\'));' . $statements;
472
        }
473
474
        if (!empty($this->cacheStack)) {
475
            $n = count($this->dynamicPlaceholders);
476
            $placeholder = "<![CDATA[YII-DYNAMIC-$n-{$this->getPlaceholderSignature()}]]>";
477
            $this->addDynamicPlaceholder($placeholder, $statements);
478
479
            return $placeholder;
480
        }
481
482
        return $this->evaluateDynamicContent($statements);
483
    }
484
485
    /**
486
     * Get source locale.
487
     *
488
     * @return Locale
489
     */
490
    public function getSourceLocale(): Locale
491
    {
492
        if ($this->sourceLocale === null) {
493
            $this->sourceLocale = Locale::create('en-US');
0 ignored issues
show
Bug introduced by
The method create() does not exist on Yiisoft\I18n\Locale. ( Ignorable by Annotation )

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

493
            /** @scrutinizer ignore-call */ 
494
            $this->sourceLocale = Locale::create('en-US');

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
494
        }
495
496
        return $this->sourceLocale;
497
    }
498
499
    /**
500
     * Set source locale.
501
     *
502
     * @param string $locale
503
     * @return self
504
     */
505
    public function setSourceLocale(string $locale): self
506
    {
507
        $this->sourceLocale = Locale::create($locale);
508
509
        return $this;
510
    }
511
512
    public function getDynamicPlaceholders(): array
513
    {
514
        return $this->dynamicPlaceholders;
515
    }
516
517
    public function setDynamicPlaceholders(array $placeholders): void
518
    {
519
        $this->dynamicPlaceholders = $placeholders;
520
    }
521
522
    public function addDynamicPlaceholder(string $placeholder, string $statements): void
523
    {
524
        foreach ($this->cacheStack as $cache) {
525
            $cache->addDynamicPlaceholder($placeholder, $statements);
526
        }
527
528
        $this->dynamicPlaceholders[$placeholder] = $statements;
529
    }
530
531
    /**
532
     * Evaluates the given PHP statements.
533
     *
534
     * This method is mainly used internally to implement dynamic content feature.
535
     *
536
     * @param string $statements the PHP statements to be evaluated.
537
     *
538
     * @return mixed the return value of the PHP statements.
539
     */
540
    public function evaluateDynamicContent(string $statements)
541
    {
542
        return eval($statements);
0 ignored issues
show
introduced by
The use of eval() is discouraged.
Loading history...
543
    }
544
545
    /**
546
     * Returns a list of currently active dynamic content class instances.
547
     *
548
     * @return DynamicContentAwareInterface[] class instances supporting dynamic contents.
549
     */
550
    public function getDynamicContents(): array
551
    {
552
        return $this->cacheStack;
553
    }
554
555
    /**
556
     * Adds a class instance supporting dynamic contents to the end of a list of currently active dynamic content class
557
     * instances.
558
     *
559
     * @param DynamicContentAwareInterface $instance class instance supporting dynamic contents.
560
     *
561
     * @return void
562
     */
563
    public function pushDynamicContent(DynamicContentAwareInterface $instance): void
564
    {
565
        $this->cacheStack[] = $instance;
566
    }
567
568
    /**
569
     * Removes a last class instance supporting dynamic contents from a list of currently active dynamic content class
570
     * instances.
571
     *
572
     * @return void
573
     */
574
    public function popDynamicContent(): void
575
    {
576
        array_pop($this->cacheStack);
577
    }
578
579
    /**
580
     * Marks the beginning of a page.
581
     *
582
     * @return void
583
     */
584
    public function beginPage(): void
585
    {
586
        ob_start();
587
        ob_implicit_flush(0);
588
589
        $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

589
        $this->eventDispatcher->dispatch(new PageBegin(/** @scrutinizer ignore-type */ $this->getViewFile()));
Loading history...
590
    }
591
592
    /**
593
     * Marks the ending of a page.
594
     *
595
     * @return void
596
     */
597
    public function endPage(): void
598
    {
599
        $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

599
        $this->eventDispatcher->dispatch(new PageEnd(/** @scrutinizer ignore-type */ $this->getViewFile()));
Loading history...
600
        ob_end_flush();
601
    }
602
}
603