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

View   D

Complexity

Total Complexity 58

Size/Duplication

Total Lines 601
Duplicated Lines 0 %

Test Coverage

Coverage 50.31%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 58
eloc 136
c 2
b 1
f 0
dl 0
loc 601
ccs 82
cts 163
cp 0.5031
rs 4.5599

37 Methods

Rating   Name   Duplication   Size   Complexity  
A getBasePath() 0 3 1
A endPage() 0 4 1
A getDynamicPlaceholders() 0 3 1
A withDefaultExtension() 0 5 1
A setBlock() 0 3 1
A getDefaultParameters() 0 3 1
A withSourceLanguage() 0 5 1
A withLanguage() 0 5 1
A withDefaultParameters() 0 5 1
A render() 0 5 1
A withTheme() 0 5 1
A __construct() 0 6 1
A withRenderers() 0 5 1
A removeBlock() 0 3 1
A getPlaceholderSignature() 0 3 1
A getBlock() 0 7 2
A hasBlock() 0 3 1
A setPlaceholderSalt() 0 3 1
A getDefaultExtension() 0 3 1
A getRequestedViewFile() 0 3 2
A renderFile() 0 35 4
A afterRender() 0 6 1
A getViewFile() 0 3 2
A beginPage() 0 6 2
A addDynamicPlaceholder() 0 7 2
A evaluateDynamicContent() 0 3 1
A renderDynamic() 0 15 3
A setDynamicPlaceholders() 0 3 1
A beforeRender() 0 6 1
A popDynamicContent() 0 3 1
A getDynamicContents() 0 3 1
B findTemplateFile() 0 27 7
A setSourceLocale() 0 5 1
A localize() 0 20 5
A withContext() 0 5 1
A getSourceLocale() 0 7 2
A pushDynamicContent() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like View often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use View, and based on these observations, apply Extract Interface, too.

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
303 2
        }  elseif (($currentViewFile = $this->getRequestedViewFile()) !== false) {
304
            // path relative to currently rendered view
305 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

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

615
        $this->eventDispatcher->dispatch(new PageBegin(/** @scrutinizer ignore-type */ $this->getViewFile()));
Loading history...
616 7
    }
617
618
    /**
619
     * Marks the ending of a page.
620
     */
621
    public function endPage(): void
622
    {
623
        $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

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