Passed
Pull Request — master (#120)
by
unknown
02:16
created

View::removeBlock()   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
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
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 View::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 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|null 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
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 array $cacheStack = [];
83
84
    /**
85
     * @var array a list of placeholders for embedding dynamic contents.
86
     */
87
    private array $dynamicPlaceholders = [];
88
89
    /**
90
     * @var string
91
     */
92
    private string $language = 'en';
93
94
    /**
95
     * @var LoggerInterface
96
     */
97
    private LoggerInterface $logger;
98
99
    /**
100
     * @var string
101
     */
102
    private string $sourceLanguage = 'en';
103
104
    /**
105
     * @var Locale|null source locale used to find localized view file.
106
     */
107
    private ?Locale $sourceLocale = null;
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 18
    public function __construct(string $basePath, Theme $theme, EventDispatcherInterface $eventDispatcher, LoggerInterface $logger)
118
    {
119 18
        $this->basePath = $basePath;
120 18
        $this->theme = $theme;
121 18
        $this->eventDispatcher = $eventDispatcher;
122 18
        $this->logger = $logger;
123 18
        $this->setPlaceholderSalt(__DIR__);
124 18
    }
125
126 18
    public function setPlaceholderSalt(string $salt): void
127
    {
128 18
        $this->placeholderSignature = dechex(crc32($salt));
129 18
    }
130
131 5
    public function getPlaceholderSignature(): string
132
    {
133 5
        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 2
    public function setDefaultParameters(array $defaultParameters): void
177
    {
178 2
        $this->defaultParameters = $defaultParameters;
179 2
    }
180
181
    /**
182
     * {@see blocks}
183
     *
184
     * @param string $id
185
     * @param string $value
186
     */
187
    public function setBlock(string $id, string $value): void
188
    {
189
        $this->blocks[$id] = $value;
190
    }
191
192
    /**
193
     * {@see blocks}
194
     *
195
     * @param string $id
196
     */
197
    public function removeBlock(string $id): void
198
    {
199
        unset($this->blocks[$id]);
200
    }
201
202
    /**
203
     * {@see blocks}
204
     *
205
     * @param string $id
206
     *
207
     * @return string
208
     */
209
    public function getBlock(string $id): string
210
    {
211
        if (isset($this->blocks[$id])) {
212
            return $this->blocks[$id];
213
        }
214
215
        throw new \InvalidArgumentException('Block: "' . $id . '" not found.');
216
    }
217
218
    /**
219
     * {@see blocks}
220
     *
221
     * @param string $id
222
     *
223
     * @return bool
224
     */
225
    public function hasBlock(string $id): bool
226
    {
227
        return isset($this->blocks[$id]);
228
    }
229
230
    /**
231
     * Renders a view.
232
     *
233
     * The view to be rendered can be specified in one of the following formats:
234
     *
235
     * - [path alias](guide:concept-aliases) (e.g. "@app/views/site/index");
236
     * - absolute path within application (e.g. "//site/index"): the view name starts with double slashes. The actual
237
     *   view file will be looked for under the [[Application::viewPath|view path]] of the application.
238
     * - absolute path within current module (e.g. "/site/index"): the view name starts with a single slash. The actual
239
     *   view file will be looked for under the [[Module::viewPath|view path]] of the [[Controller::module|current module]].
240
     * - relative view (e.g. "index"): the view name does not start with `@` or `/`. The corresponding view file will be
241
     *   looked for under the {@see ViewContextInterface::getViewPath()} of the view `$context`.
242
     *   If `$context` is not given, it will be looked for under the directory containing the view currently
243
     *   being rendered (i.e., this happens when rendering a view within another view).
244
     *
245
     * @param string $view the view name.
246
     * @param array $parameters the parameters (name-value pairs) that will be extracted and made available in the view
247
     * file.
248
     * @param ViewContextInterface|null $context the context to be assigned to the view and can later be accessed via
249
     * {@see context} in the view. If the context implements {@see ViewContextInterface}, it may also be used to locate
250
     * the view file corresponding to a relative view name.
251
     *
252
     * @throws \RuntimeException if the view cannot be resolved.
253
     * @throws ViewNotFoundException if the view file does not exist.
254
     * @throws \Throwable
255
     *
256
     * {@see renderFile()}
257
     *
258
     * @return string the rendering result
259
     */
260 4
    public function render(string $view, array $parameters = [], ?ViewContextInterface $context = null): string
261
    {
262 4
        $viewFile = $this->findTemplateFile($view, $context);
263
264 4
        return $this->renderFile($viewFile, $parameters, $context);
265
    }
266
267
    /**
268
     * Finds the view file based on the given view name.
269
     *
270
     * @param string $view the view name or the [path alias](guide:concept-aliases) of the view file. Please refer to
271
     * {@see render()} on how to specify this parameter.
272
     * @param ViewContextInterface|null $context the context to be assigned to the view and can later be accessed via
273
     * {@see context} in the view. If the context implements {@see ViewContextInterface}, it may also be used to locate the
274
     * view file corresponding to a relative view name.
275
     *
276
     * @throws \RuntimeException if a relative view name is given while there is no active context to determine the
277
     * corresponding view file.
278
     *
279
     * @return string the view file path. Note that the file may not exist.
280
     */
281 4
    protected function findTemplateFile(string $view, ?ViewContextInterface $context = null): string
282
    {
283 4
        if (strncmp($view, '//', 2) === 0) {
284
            // path relative to basePath e.g. "//layouts/main"
285 4
            $file = $this->basePath . '/' . ltrim($view, '/');
286 1
        } elseif ($context instanceof ViewContextInterface) {
287
            // path provided by context
288
            $file = $context->getViewPath() . '/' . $view;
289 1
        } elseif (($currentViewFile = $this->getRequestedViewFile()) !== false) {
290
            // path relative to currently rendered view
291 1
            $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

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

604
        $this->eventDispatcher->dispatch(new PageBegin(/** @scrutinizer ignore-type */ $this->getViewFile()));
Loading history...
605 4
    }
606
607
    /**
608
     * Marks the ending of a page.
609
     */
610
    public function endPage(): void
611
    {
612
        $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

612
        $this->eventDispatcher->dispatch(new PageEnd(/** @scrutinizer ignore-type */ $this->getViewFile()));
Loading history...
613
        ob_end_flush();
614
    }
615
}
616