Passed
Push — master ( 5542c1...1e8623 )
by Alexander
01:51
created

WebView   B

Complexity

Total Complexity 49

Size/Duplication

Total Lines 560
Duplicated Lines 0 %

Test Coverage

Coverage 52.94%

Importance

Changes 0
Metric Value
wmc 49
eloc 117
dl 0
loc 560
ccs 63
cts 119
cp 0.5294
rs 8.48
c 0
b 0
f 0

21 Methods

Rating   Name   Duplication   Size   Complexity  
A registerLinkTag() 0 6 2
A renderBodyBeginHtml() 0 11 4
A clear() 0 8 1
A registerJs() 0 4 2
A registerMetaTag() 0 6 2
A registerJsFile() 0 6 2
A setTitle() 0 3 1
A head() 0 3 1
A registerCssFile() 0 5 2
A renderAjax() 0 15 1
B renderBodyEndHtml() 0 37 11
A setJsFiles() 0 6 2
A beginBody() 0 4 1
B renderHeadHtml() 0 24 8
A getTitle() 0 3 1
A endBody() 0 4 1
A endPage() 0 13 1
A registerCsrfMetaTags() 0 3 1
A setCssFiles() 0 6 2
A registerCss() 0 4 2
A registerJsVar() 0 4 1

How to fix   Complexity   

Complex Class

Complex classes like WebView 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 WebView, 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 Yiisoft\Html\Html;
8
use Yiisoft\Arrays\ArrayHelper;
9
use Yiisoft\View\Event\BodyBegin;
10
use Yiisoft\View\Event\BodyEnd;
11
use Yiisoft\View\Event\PageEnd;
12
13
/**
14
 * View represents a view object in the MVC pattern.
15
 *
16
 * View provides a set of methods (e.g. {@see render()} for rendering purpose.
17
 *
18
 * You can modify its configuration by adding an array to your application config under `components` as it is shown in
19
 * the following example:
20
 *
21
 * ```php
22
 * 'view' => [
23
 *     'theme' => 'app\themes\MyTheme',
24
 *     'renderers' => [
25
 *         // you may add Smarty or Twig renderer here
26
 *     ]
27
 *     // ...
28
 * ]
29
 * ```
30
 *
31
 * For more details and usage information on View, see the [guide article on views](guide:structure-views).
32
 */
33
class WebView extends View
34
{
35
    /**
36
     * The location of registered JavaScript code block or files.
37
     * This means the location is in the head section.
38
     */
39
    public const POSITION_HEAD = 1;
40
41
    /**
42
     * The location of registered JavaScript code block or files.
43
     * This means the location is at the beginning of the body section.
44
     */
45
    public const POSITION_BEGIN = 2;
46
47
    /**
48
     * The location of registered JavaScript code block or files.
49
     * This means the location is at the end of the body section.
50
     */
51
    public const POSITION_END = 3;
52
53
    /**
54
     * The location of registered JavaScript code block.
55
     * This means the JavaScript code block will be executed when HTML document composition is ready.
56
     */
57
    public const POSITION_READY = 4;
58
59
    /**
60
     * The location of registered JavaScript code block.
61
     * This means the JavaScript code block will be executed when HTML page is completely loaded.
62
     */
63
    public const POSITION_LOAD = 5;
64
65
    /**
66
     * This is internally used as the placeholder for receiving the content registered for the head section.
67
     */
68
    private const PLACEHOLDER_HEAD = '<![CDATA[YII-BLOCK-HEAD]]>';
69
70
    /**
71
     * This is internally used as the placeholder for receiving the content registered for the beginning of the body
72
     * section.
73
     */
74
    private const PLACEHOLDER_BODY_BEGIN = '<![CDATA[YII-BLOCK-BODY-BEGIN]]>';
75
76
    /**
77
     * This is internally used as the placeholder for receiving the content registered for the end of the body section.
78
     */
79
    private const PLACEHOLDER_BODY_END = '<![CDATA[YII-BLOCK-BODY-END]]>';
80
81
    /**
82
     * @var string the page title
83
     */
84
    private string $title;
85
86
    /**
87
     * @var array the registered meta tags.
88
     *
89
     * {@see registerMetaTag()}
90
     */
91
    private array $metaTags = [];
92
93
    /**
94
     * @var array the registered link tags.
95
     *
96
     * {@see registerLinkTag()}
97
     */
98
    private array $linkTags = [];
99
100
    /**
101
     * @var array the registered CSS code blocks.
102
     *
103
     * {@see registerCss()}
104
     */
105
    private array $css = [];
106
107
    /**
108
     * @var array the registered CSS files.
109
     *
110
     * {@see registerCssFile()}
111
     */
112
    private array $cssFiles = [];
113
114
    /**
115
     * @var array the registered JS code blocks
116
     *
117
     * {@see registerJs()}
118
     */
119
    private array $js = [];
120
121
    /**
122
     * @var array the registered JS files.
123
     *
124
     * {@see registerJsFile()}
125
     */
126
    private array $jsFiles = [];
127
128
    /**
129
     * Marks the position of an HTML head section.
130
     */
131 3
    public function head(): void
132
    {
133 3
        echo self::PLACEHOLDER_HEAD;
134
    }
135
136
    /**
137
     * Marks the beginning of an HTML body section.
138
     */
139 3
    public function beginBody(): void
140
    {
141 3
        echo self::PLACEHOLDER_BODY_BEGIN;
142 3
        $this->eventDispatcher->dispatch(new BodyBegin($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\BodyBegin::__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

142
        $this->eventDispatcher->dispatch(new BodyBegin(/** @scrutinizer ignore-type */ $this->getViewFile()));
Loading history...
143
    }
144
145
    /**
146
     * Marks the ending of an HTML body section.
147
     */
148 3
    public function endBody(): void
149
    {
150 3
        $this->eventDispatcher->dispatch(new BodyEnd($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\BodyEnd::__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

150
        $this->eventDispatcher->dispatch(new BodyEnd(/** @scrutinizer ignore-type */ $this->getViewFile()));
Loading history...
151 3
        echo self::PLACEHOLDER_BODY_END;
152
    }
153
154
    /**
155
     * Marks the ending of an HTML page.
156
     *
157
     * @param bool $ajaxMode whether the view is rendering in AJAX mode. If true, the JS scripts registered at
158
     * {@see POSITION_READY} and {@see POSITION_LOAD} positions will be rendered at the end of the view like
159
     * normal scripts.
160
     */
161 3
    public function endPage($ajaxMode = false): void
162
    {
163 3
        $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

163
        $this->eventDispatcher->dispatch(new PageEnd(/** @scrutinizer ignore-type */ $this->getViewFile()));
Loading history...
164
165 3
        $content = ob_get_clean();
166
167 3
        echo strtr($content, [
168 3
            self::PLACEHOLDER_HEAD => $this->renderHeadHtml(),
169 3
            self::PLACEHOLDER_BODY_BEGIN => $this->renderBodyBeginHtml(),
170 3
            self::PLACEHOLDER_BODY_END => $this->renderBodyEndHtml($ajaxMode),
171
        ]);
172
173 3
        $this->clear();
174
    }
175
176
    /**
177
     * Renders a view in response to an AJAX request.
178
     *
179
     * This method is similar to {@see render()} except that it will surround the view being rendered with the calls of
180
     * {@see beginPage()}, {@see head()}, {@see beginBody()}, {@see endBody()} and {@see endPage()}. By doing so, the
181
     * method is able to inject into the rendering result with JS/CSS scripts and files that are registered with the
182
     * view.
183
     *
184
     * @param string $view the view name. Please refer to {@see render()} on how to specify this parameter.
185
     * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view
186
     * file.
187
     * @param ViewContextInterface|null $context the context that the view should use for rendering the view. If null,
188
     * existing {@see context} will be used.
189
     *
190
     * @return string the rendering result
191
     *
192
     * {@see render()}
193
     */
194
    public function renderAjax(string $view, array $params = [], ?ViewContextInterface $context = null): string
195
    {
196
        $viewFile = $this->findTemplateFile($view, $context);
197
198
        ob_start();
199
        ob_implicit_flush(0);
200
201
        $this->beginPage();
202
        $this->head();
203
        $this->beginBody();
204
        echo $this->renderFile($viewFile, $params, $context);
205
        $this->endBody();
206
        $this->endPage(true);
207
208
        return ob_get_clean();
209
    }
210
211
    /**
212
     * Clears up the registered meta tags, link tags, css/js scripts and files.
213
     *
214
     * @return void
215
     */
216 3
    public function clear(): void
217
    {
218 3
        $this->metaTags = [];
219 3
        $this->linkTags = [];
220 3
        $this->css = [];
221 3
        $this->cssFiles = [];
222 3
        $this->js = [];
223 3
        $this->jsFiles = [];
224
    }
225
226
    /**
227
     * Registers a meta tag.
228
     *
229
     * For example, a description meta tag can be added like the following:
230
     *
231
     * ```php
232
     * $view->registerMetaTag([
233
     *     'name' => 'description',
234
     *     'content' => 'This website is about funny raccoons.'
235
     * ]);
236
     * ```
237
     *
238
     * will result in the meta tag `<meta name="description" content="This website is about funny raccoons.">`.
239
     *
240
     * @param array $options the HTML attributes for the meta tag.
241
     * @param string $key the key that identifies the meta tag. If two meta tags are registered with the same key, the
242
     * latter will overwrite the former. If this is null, the new meta tag will be appended to the
243
     * existing ones.
244
     *
245
     * @return void
246
     */
247
    public function registerMetaTag(array $options, string $key = null): void
248
    {
249
        if ($key === null) {
250
            $this->metaTags[] = Html::tag('meta', '', $options);
251
        } else {
252
            $this->metaTags[$key] = Html::tag('meta', '', $options);
253
        }
254
    }
255
256
    /**
257
     * Registers a link tag.
258
     *
259
     * For example, a link tag for a custom [favicon](http://www.w3.org/2005/10/howto-favicon) can be added like the
260
     * following:
261
     *
262
     * ```php
263
     * $view->registerLinkTag(['rel' => 'icon', 'type' => 'image/png', 'href' => '/myicon.png']);
264
     * ```
265
     *
266
     * which will result in the following HTML: `<link rel="icon" type="image/png" href="/myicon.png">`.
267
     *
268
     * **Note:** To register link tags for CSS stylesheets, use {@see registerCssFile()]} instead, which has more
269
     * options for this kind of link tag.
270
     *
271
     * @param array $options the HTML attributes for the link tag.
272
     * @param string|null $key the key that identifies the link tag. If two link tags are registered with the same
273
     * key, the latter will overwrite the former. If this is null, the new link tag will be appended
274
     * to the existing ones.
275
     */
276
    public function registerLinkTag(array $options, ?string $key = null): void
277
    {
278
        if ($key === null) {
279
            $this->linkTags[] = Html::tag('link', '', $options);
280
        } else {
281
            $this->linkTags[$key] = Html::tag('link', '', $options);
282
        }
283
    }
284
285
    /**
286
     * Registers CSRF meta tags.
287
     *
288
     * They are rendered dynamically to retrieve a new CSRF token for each request.
289
     *
290
     * ```php
291
     * $view->registerCsrfMetaTags();
292
     * ```
293
     *
294
     * The above code will result in `<meta name="csrf-param" content="[\Yiisoft\Web\Request::$csrfParam]">` and
295
     * `<meta name="csrf-token" content="tTNpWKpdy-bx8ZmIq9R72...K1y8IP3XGkzZA==">` added to the page.
296
     *
297
     * Note: Hidden CSRF input of ActiveForm will be automatically refreshed by calling `window.yii.refreshCsrfToken()`
298
     * from `yii.js`.
299
     */
300
    public function registerCsrfMetaTags(): void
301
    {
302
        $this->metaTags['csrf_meta_tags'] = $this->renderDynamic('return Yiisoft\Html\Html::csrfMetaTags();');
303
    }
304
305
    /**
306
     * Registers a CSS code block.
307
     *
308
     * @param string $css the content of the CSS code block to be registered
309
     * @param array $options the HTML attributes for the `<style>`-tag.
310
     * @param string $key the key that identifies the CSS code block. If null, it will use $css as the key. If two CSS
311
     * code blocks are registered with the same key, the latter will overwrite the former.
312
     */
313
    public function registerCss(string $css, array $options = [], string $key = null): void
314
    {
315
        $key = $key ?: md5($css);
316
        $this->css[$key] = Html::style($css, $options);
317
    }
318
319
    /**
320
     * Registers a CSS file.
321
     *
322
     * This method should be used for simple registration of CSS files. If you want to use features of
323
     * {@see \Yiisoft\Assets\AssetManager} like appending timestamps to the URL and file publishing options, use
324
     * {@see \Yiisoft\Assets\AssetBundle}.
325
     *
326
     * @param string $url the CSS file to be registered.
327
     * @param array $options the HTML attributes for the link tag. Please refer to {@see \Yiisoft\Html\Html::cssFile()}
328
     * for the supported options.
329
     *
330
     * @param string $key the key that identifies the CSS script file. If null, it will use $url as the key. If two CSS
331
     * files are registered with the same key, the latter will overwrite the former.
332
     *
333
     * @return void
334
     */
335 1
    public function registerCssFile(string $url, array $options = [], string $key = null): void
336
    {
337 1
        $key = $key ?: $url;
338
339 1
        $this->cssFiles[$key] = Html::cssFile($url, $options);
340
    }
341
342
    /**
343
     * Registers a JS code block.
344
     *
345
     * @param string $js the JS code block to be registered
346
     * @param int $position the position at which the JS script tag should be inserted in a page.
347
     *
348
     * The possible values are:
349
     *
350
     * - {@see POSITION_HEAD}: in the head section
351
     * - {@see POSITION_BEGIN}: at the beginning of the body section
352
     * - {@see POSITION_END}: at the end of the body section. This is the default value.
353
     * - {@see POSITION_LOAD}: executed when HTML page is completely loaded.
354
     * - {@see POSITION_READY}: executed when HTML document composition is ready.
355
     *
356
     * @param string $key the key that identifies the JS code block. If null, it will use $js as the key. If two JS code
357
     * blocks are registered with the same key, the latter will overwrite the former.
358
     *
359
     * @return void
360
     */
361 1
    public function registerJs(string $js, int $position = self::POSITION_END, string $key = null): void
362
    {
363 1
        $key = $key ?: md5($js);
364 1
        $this->js[$position][$key] = $js;
365
    }
366
367
    /**
368
     * Registers a JS file.
369
     *
370
     * This method should be used for simple registration of JS files. If you want to use features of
371
     * {@see \Yiisoft\Assets\AssetManager} like appending timestamps to the URL and file publishing options, use
372
     * {@see \Yiisoft\Assets\AssetBundle}.
373
     *
374
     * @param string $url the JS file to be registered.
375
     * @param array $options the HTML attributes for the script tag. The following options are specially handled and
376
     * are not treated as HTML attributes:
377
     *
378
     * - `position`: specifies where the JS script tag should be inserted in a page. The possible values are:
379
     *     * {@see POSITION_HEAD}: in the head section
380
     *     * {@see POSITION_BEGIN}: at the beginning of the body section
381
     *     * {@see POSITION_END}: at the end of the body section. This is the default value.
382
     *
383
     * Please refer to {@see \Yiisoft\Html\Html::jsFile()} for other supported options.
384
     *
385
     * @param string $key the key that identifies the JS script file. If null, it will use $url as the key. If two JS
386
     * files are registered with the same key at the same position, the latter will overwrite the former.
387
     * Note that position option takes precedence, thus files registered with the same key, but different
388
     * position option will not override each other.
389
     *
390
     * @return void
391
     */
392 1
    public function registerJsFile(string $url, array $options = [], string $key = null): void
393
    {
394 1
        $key = $key ?: $url;
395
396 1
        $position = ArrayHelper::remove($options, 'position', self::POSITION_END);
397 1
        $this->jsFiles[$position][$key] = Html::jsFile($url, $options);
398
    }
399
400
    /**
401
     * Registers a JS code block defining a variable. The name of variable will be used as key, preventing duplicated
402
     * variable names.
403
     *
404
     * @param string $name Name of the variable
405
     * @param array|string $value Value of the variable
406
     * @param int $position the position in a page at which the JavaScript variable should be inserted.
407
     *
408
     * The possible values are:
409
     *
410
     * - {@see POSITION_HEAD}: in the head section. This is the default value.
411
     * - {@see POSITION_BEGIN}: at the beginning of the body section.
412
     * - {@see POSITION_END}: at the end of the body section.
413
     * - {@see POSITION_LOAD}: enclosed within jQuery(window).load().
414
     *   Note that by using this position, the method will automatically register the jQuery js file.
415
     * - {@see POSITION_READY}: enclosed within jQuery(document).ready().
416
     *   Note that by using this position, the method will automatically register the jQuery js file.
417
     */
418 1
    public function registerJsVar(string $name, $value, int $position = self::POSITION_HEAD): void
419
    {
420 1
        $js = sprintf('var %s = %s;', $name, \Yiisoft\Json\Json::htmlEncode($value));
421 1
        $this->registerJs($js, $position, $name);
422
    }
423
424
    /**
425
     * Renders the content to be inserted in the head section.
426
     *
427
     * The content is rendered using the registered meta tags, link tags, CSS/JS code blocks and files.
428
     *
429
     * @return string the rendered content
430
     */
431 3
    protected function renderHeadHtml(): string
432
    {
433 3
        $lines = [];
434 3
        if (!empty($this->metaTags)) {
435
            $lines[] = implode("\n", $this->metaTags);
436
        }
437
438 3
        if (!empty($this->linkTags)) {
439
            $lines[] = implode("\n", $this->linkTags);
440
        }
441 3
        if (!empty($this->cssFiles)) {
442 1
            $lines[] = implode("\n", $this->cssFiles);
443
        }
444 3
        if (!empty($this->css)) {
445
            $lines[] = implode("\n", $this->css);
446
        }
447 3
        if (!empty($this->jsFiles[self::POSITION_HEAD])) {
448 1
            $lines[] = implode("\n", $this->jsFiles[self::POSITION_HEAD]);
449
        }
450 3
        if (!empty($this->js[self::POSITION_HEAD])) {
451 1
            $lines[] = Html::script(implode("\n", $this->js[self::POSITION_HEAD]));
452
        }
453
454 3
        return empty($lines) ? '' : implode("\n", $lines);
455
    }
456
457
    /**
458
     * Renders the content to be inserted at the beginning of the body section.
459
     *
460
     * The content is rendered using the registered JS code blocks and files.
461
     *
462
     * @return string the rendered content
463
     */
464 3
    protected function renderBodyBeginHtml(): string
465
    {
466 3
        $lines = [];
467 3
        if (!empty($this->jsFiles[self::POSITION_BEGIN])) {
468 1
            $lines[] = implode("\n", $this->jsFiles[self::POSITION_BEGIN]);
469
        }
470 3
        if (!empty($this->js[self::POSITION_BEGIN])) {
471
            $lines[] = Html::script(implode("\n", $this->js[self::POSITION_BEGIN]));
472
        }
473
474 3
        return empty($lines) ? '' : implode("\n", $lines);
475
    }
476
477
    /**
478
     * Renders the content to be inserted at the end of the body section.
479
     *
480
     * The content is rendered using the registered JS code blocks and files.
481
     *
482
     * @param bool $ajaxMode whether the view is rendering in AJAX mode. If true, the JS scripts registered at
483
     * {@see POSITION_READY} and {@see POSITION_LOAD} positions will be rendered at the end of the view like normal
484
     * scripts.
485
     *
486
     * @return string the rendered content
487
     */
488 3
    protected function renderBodyEndHtml(bool $ajaxMode): string
489
    {
490 3
        $lines = [];
491
492 3
        if (!empty($this->jsFiles[self::POSITION_END])) {
493 1
            $lines[] = implode("\n", $this->jsFiles[self::POSITION_END]);
494
        }
495
496 3
        if ($ajaxMode) {
497
            $scripts = [];
498
            if (!empty($this->js[self::POSITION_END])) {
499
                $scripts[] = implode("\n", $this->js[self::POSITION_END]);
500
            }
501
            if (!empty($this->js[self::POSITION_READY])) {
502
                $scripts[] = implode("\n", $this->js[self::POSITION_READY]);
503
            }
504
            if (!empty($this->js[self::POSITION_LOAD])) {
505
                $scripts[] = implode("\n", $this->js[self::POSITION_LOAD]);
506
            }
507
            if (!empty($scripts)) {
508
                $lines[] = Html::script(implode("\n", $scripts));
509
            }
510
        } else {
511 3
            if (!empty($this->js[self::POSITION_END])) {
512
                $lines[] = Html::script(implode("\n", $this->js[self::POSITION_END]));
513
            }
514 3
            if (!empty($this->js[self::POSITION_READY])) {
515
                $js = "document.addEventListener('DOMContentLoaded', function(event) {\n" . implode("\n", $this->js[self::POSITION_READY]) . "\n});";
516
                $lines[] = Html::script($js, ['type' => 'text/javascript']);
517
            }
518 3
            if (!empty($this->js[self::POSITION_LOAD])) {
519
                $js = "window.addEventListener('load', function (event) {\n" . implode("\n", $this->js[self::POSITION_LOAD]) . "\n});";
520
                $lines[] = Html::script($js, ['type' => 'text/javascript']);
521
            }
522
        }
523
524 3
        return empty($lines) ? '' : implode("\n", $lines);
525
    }
526
527
    /**
528
     * Get title in views.
529
     *
530
     *
531
     * in Layout:
532
     *
533
     * ```php
534
     * <title><?= Html::encode($this->getTitle()) ?></title>
535
     * ```
536
     *
537
     * in Views:
538
     *
539
     * ```php
540
     * $this->setTitle('Web Application - Yii 3.0.');
541
     * ```
542
     *
543
     * @return string
544
     */
545
    public function getTitle(): string
546
    {
547
        return $this->title;
548
    }
549
550
    /**
551
     * It processes the CSS configuration generated by the asset manager and converts it into HTML code.
552
     *
553
     * @param array $cssFiles
554
     * @return void
555
     */
556
    public function setCssFiles(array $cssFiles): void
557
    {
558
        foreach ($cssFiles as $key => $value) {
559
            $this->registerCssFile(
560
                $cssFiles[$key]['url'],
561
                $cssFiles[$key]['attributes']
562
            );
563
        }
564
    }
565
566
    /**
567
     * It processes the JS configuration generated by the asset manager and converts it into HTML code.
568
     *
569
     * @param array $jsFiles
570
     * @return void
571
     */
572
    public function setJsFiles(array $jsFiles): void
573
    {
574
        foreach ($jsFiles as $key => $value) {
575
            $this->registerJsFile(
576
                $jsFiles[$key]['url'],
577
                $jsFiles[$key]['attributes']
578
            );
579
        }
580
    }
581
582
    /**
583
     * Set title in views.
584
     *
585
     * {@see getTitle()}
586
     *
587
     * @param string $value
588
     * @return void
589
     */
590
    public function setTitle($value): void
591
    {
592
        $this->title = $value;
593
    }
594
}
595