Completed
Pull Request — master (#52)
by Alexander
03:31
created

WebView   F

Complexity

Total Complexity 64

Size/Duplication

Total Lines 671
Duplicated Lines 0 %

Test Coverage

Coverage 62.5%

Importance

Changes 5
Bugs 0 Features 0
Metric Value
wmc 64
eloc 169
dl 0
loc 671
ccs 105
cts 168
cp 0.625
rs 3.28
c 5
b 0
f 0

23 Methods

Rating   Name   Duplication   Size   Complexity  
A setAssetManager() 0 3 1
A clear() 0 9 1
A head() 0 3 1
A registerAssetFiles() 0 16 4
A renderAjax() 0 15 1
A beginBody() 0 4 1
A endBody() 0 7 2
A endPage() 0 13 1
A getAssetManager() 0 3 1
A getAssetBundles() 0 3 1
A registerLinkTag() 0 6 2
A renderBodyBeginHtml() 0 11 4
A registerJs() 0 4 2
A registerMetaTag() 0 6 2
A registerJsFile() 0 18 4
A registerCssFile() 0 18 4
B registerAssetBundle() 0 38 8
B renderBodyEndHtml() 0 37 11
B renderHeadHtml() 0 24 8
A registerCsrfMetaTags() 0 3 1
A registerCss() 0 4 2
A createBundle() 0 9 1
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
declare(strict_types = 1);
3
4
namespace Yiisoft\View;
5
6
use Yiisoft\Asset\AssetBundle;
7
use Yiisoft\Asset\AssetManager;
8
use Yiisoft\Html\Html;
9
use Yiisoft\Arrays\ArrayHelper;
10
use Yiisoft\View\Event\BodyBegin;
11
use Yiisoft\View\Event\BodyEnd;
12
use Yiisoft\View\Event\PageEnd;
13
14
/**
15
 * View represents a view object in the MVC pattern.
16
 *
17
 * View provides a set of methods (e.g. {@see render()} for rendering purpose.
18
 *
19
 * You can modify its configuration by adding an array to your application config under `components` as it is shown in
20
 * the following example:
21
 *
22
 * ```php
23
 * 'view' => [
24
 *     'theme' => 'app\themes\MyTheme',
25
 *     'renderers' => [
26
 *         // you may add Smarty or Twig renderer here
27
 *     ]
28
 *     // ...
29
 * ]
30
 * ```
31
 *
32
 * For more details and usage information on View, see the [guide article on views](guide:structure-views).
33
 */
34
class WebView extends View
35
{
36
    /**
37
     * The location of registered JavaScript code block or files.
38
     * This means the location is in the head section.
39
     */
40
    public const POS_HEAD = 1;
41
42
    /**
43
     * The location of registered JavaScript code block or files.
44
     * This means the location is at the beginning of the body section.
45
     */
46
    public const POS_BEGIN = 2;
47
48
    /**
49
     * The location of registered JavaScript code block or files.
50
     * This means the location is at the end of the body section.
51
     */
52
    public const POS_END = 3;
53
54
    /**
55
     * The location of registered JavaScript code block.
56
     * This means the JavaScript code block will be executed when HTML document composition is ready.
57
     */
58
    public const POS_READY = 4;
59
60
    /**
61
     * The location of registered JavaScript code block.
62
     * This means the JavaScript code block will be executed when HTML page is completely loaded.
63
     */
64
    public const POS_LOAD = 5;
65
66
    /**
67
     * This is internally used as the placeholder for receiving the content registered for the head section.
68
     */
69
    private const PH_HEAD = '<![CDATA[YII-BLOCK-HEAD]]>';
70
71
    /**
72
     * This is internally used as the placeholder for receiving the content registered for the beginning of the body
73
     * section.
74
     */
75
    private const PH_BODY_BEGIN = '<![CDATA[YII-BLOCK-BODY-BEGIN]]>';
76
77
    /**
78
     * This is internally used as the placeholder for receiving the content registered for the end of the body section.
79
     */
80
    private const PH_BODY_END = '<![CDATA[YII-BLOCK-BODY-END]]>';
81
82
    /**
83
     * @var AssetBundle[] list of the registered asset bundles. The keys are the bundle names, and the values
84
     * are the registered {@see AssetBundle} objects.
85
     *
86
     * {@see registerAssetBundle()}
87
     */
88
    private $assetBundles = [];
89
90
    /**
91
     * @var AssetManager $assetManager
92
     */
93
    private $assetManager;
94
95
    /**
96
     * @var string the page title
97
     */
98
    private $title;
0 ignored issues
show
introduced by
The private property $title is not used, and could be removed.
Loading history...
99
100
    /**
101
     * @var array the registered meta tags.
102
     *
103
     * {@see registerMetaTag()}
104
     */
105
    private $metaTags = [];
106
107
    /**
108
     * @var array the registered link tags.
109
     *
110
     * {@see registerLinkTag()}
111
     */
112
    private $linkTags = [];
113
114
    /**
115
     * @var array the registered CSS code blocks.
116
     *
117
     * {@see registerCss()}
118
     */
119
    private $css = [];
120
121
    /**
122
     * @var array the registered CSS files.
123
     *
124
     * {@see registerCssFile()}
125
     */
126
    private $cssFiles = [];
127
128
    /**
129
     * @var array the registered JS code blocks
130
     *
131
     * {@see registerJs()}
132
     */
133
    private $js = [];
134
135
    /**
136
     * @var array the registered JS files.
137
     *
138
     * {@see registerJsFile()}
139
     */
140
    private $jsFiles = [];
141
142
    /**
143
     * Marks the position of an HTML head section.
144
     */
145 32
    public function head(): void
146
    {
147 32
        echo self::PH_HEAD;
148
    }
149
150
    /**
151
     * Marks the beginning of an HTML body section.
152
     */
153 32
    public function beginBody(): void
154
    {
155 32
        echo self::PH_BODY_BEGIN;
156 32
        $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

156
        $this->eventDispatcher->dispatch(new BodyBegin(/** @scrutinizer ignore-type */ $this->getViewFile()));
Loading history...
157
    }
158
159
    /**
160
     * Marks the ending of an HTML body section.
161
     */
162 32
    public function endBody(): void
163
    {
164 32
        $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

164
        $this->eventDispatcher->dispatch(new BodyEnd(/** @scrutinizer ignore-type */ $this->getViewFile()));
Loading history...
165 32
        echo self::PH_BODY_END;
166
167 32
        foreach (array_keys($this->assetBundles) as $bundle) {
168 8
            $this->registerAssetFiles($bundle);
169
        }
170
    }
171
172
    /**
173
     * Marks the ending of an HTML page.
174
     *
175
     * @param bool $ajaxMode whether the view is rendering in AJAX mode. If true, the JS scripts registered at
176
     * {@see POS_READY} and {@see POS_LOAD} positions will be rendered at the end of the view like
177
     * normal scripts.
178
     */
179 32
    public function endPage($ajaxMode = false): void
180
    {
181 32
        $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

181
        $this->eventDispatcher->dispatch(new PageEnd(/** @scrutinizer ignore-type */ $this->getViewFile()));
Loading history...
182
183 32
        $content = ob_get_clean();
184
185 32
        echo strtr($content, [
186 32
            self::PH_HEAD => $this->renderHeadHtml(),
187 32
            self::PH_BODY_BEGIN => $this->renderBodyBeginHtml(),
188 32
            self::PH_BODY_END => $this->renderBodyEndHtml($ajaxMode),
189
        ]);
190
191 32
        $this->clear();
192
    }
193
194
    /**
195
     * Renders a view in response to an AJAX request.
196
     *
197
     * This method is similar to {@see render()} except that it will surround the view being rendered with the calls of
198
     * {@see beginPage()}, {@see head()}, {@see beginBody()}, {@see endBody()} and {@see endPage()}. By doing so, the
199
     * method is able to inject into the rendering result with JS/CSS scripts and files that are registered with the
200
     * view.
201
     *
202
     * @param string $view the view name. Please refer to [[render()]] on how to specify this parameter.
203
     * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view
204
     * file.
205
     * @param object $context the context that the view should use for rendering the view. If null, existing [[context]]
206
     * will be used.
207
     *
208
     * @return string the rendering result
209
     *
210
     * {@see render()}
211
     */
212
    public function renderAjax(string $view, array $params = [], $context = null): string
213
    {
214
        $viewFile = $this->findViewFile($view, $context);
0 ignored issues
show
Bug introduced by
The method findViewFile() does not exist on Yiisoft\View\WebView. ( Ignorable by Annotation )

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

214
        /** @scrutinizer ignore-call */ 
215
        $viewFile = $this->findViewFile($view, $context);

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...
215
216
        ob_start();
217
        ob_implicit_flush(0);
218
219
        $this->beginPage();
220
        $this->head();
221
        $this->beginBody();
222
        echo $this->renderFile($viewFile, $params, $context);
223
        $this->endBody();
224
        $this->endPage(true);
225
226
        return ob_get_clean();
227
    }
228
229
    /**
230
     * Registers the asset manager being used by this view object.
231
     *
232
     * @return array the asset manager. Defaults to the "assetManager" application component.
233
     */
234 10
    public function getAssetBundles(): array
235
    {
236 10
        return $this->assetBundles;
237
    }
238
239
    /**
240
     * Registers the asset manager being used by this view object.
241
     *
242
     * @return AssetManager the asset manager. Defaults to the "assetManager" application component.
243
     */
244 33
    public function getAssetManager(): AssetManager
245
    {
246 33
        return $this->assetManager;
247
    }
248
249
    /**
250
     * Sets the asset manager.
251
     *
252
     * @param AssetManager $value the asset manager
253
     *
254
     * @return void
255
     */
256 78
    public function setAssetManager(AssetManager $value): void
257
    {
258 78
        $this->assetManager = $value;
259
    }
260
261
    /**
262
     * Clears up the registered meta tags, link tags, css/js scripts and files.
263
     *
264
     * @return void
265
     */
266 32
    public function clear(): void
267
    {
268 32
        $this->metaTags = [];
269 32
        $this->linkTags = [];
270 32
        $this->css = [];
271 32
        $this->cssFiles = [];
272 32
        $this->js = [];
273 32
        $this->jsFiles = [];
274 32
        $this->assetBundles = [];
275
    }
276
277
    /**
278
     * Registers all files provided by an asset bundle including depending bundles files.
279
     *
280
     * Removes a bundle from {@see assetBundles} once files are registered.
281
     *
282
     * @param string $name name of the bundle to register
283
     *
284
     * @return void
285
     */
286 8
    protected function registerAssetFiles(string $name): void
287
    {
288 8
        if (!isset($this->assetBundles[$name])) {
289 7
            return;
290
        }
291
292 8
        $bundle = $this->assetBundles[$name];
293
294 8
        if ($bundle) {
0 ignored issues
show
introduced by
$bundle is of type Yiisoft\Asset\AssetBundle, thus it always evaluated to true.
Loading history...
295 8
            foreach ($bundle->depends as $dep) {
296 7
                $this->registerAssetFiles($dep);
297
            }
298 8
            $bundle->registerAssetFiles($this);
299
        }
300
301 8
        unset($this->assetBundles[$name]);
302
    }
303
304
    /**
305
     * Registers the named asset bundle.
306
     *
307
     * All dependent asset bundles will be registered.
308
     *
309
     * @param string $name the class name of the asset bundle (without the leading backslash)
310
     * @param int|null $position if set, this forces a minimum position for javascript files. This will adjust depending
311
     * assets javascript file position or fail if requirement can not be met. If this is null, asset
312
     * bundles position settings will not be changed.
313
     *
314
     * {@see registerJsFile()} for more details on javascript position.
315
     *
316
     * @throws \RuntimeException if the asset bundle does not exist or a circular dependency is detected
317
     *
318
     * @return AssetBundle the registered asset bundle instance
319
     */
320 12
    public function registerAssetBundle(string $name, ?int $position = null): AssetBundle
321
    {
322 12
        if (!isset($this->assetBundles[$name])) {
323 12
            $bundle = $this->getAssetManager()->getBundle($name);
324
325 12
            $this->assetBundles[$name] = false;
326
327
            // register dependencies
328
329 12
            $pos = $bundle->jsOptions['position'] ?? null;
330
331 12
            foreach ($bundle->depends as $dep) {
332 10
                $this->registerAssetBundle($dep, $pos);
333
            }
334
335 11
            $this->assetBundles[$name] = $bundle;
336 8
        } elseif ($this->assetBundles[$name] === false) {
0 ignored issues
show
introduced by
The condition $this->assetBundles[$name] === false is always false.
Loading history...
337 1
            throw new \RuntimeException("A circular dependency is detected for bundle '$name'.");
338
        } else {
339 7
            $bundle = $this->assetBundles[$name];
340
        }
341
342 11
        if ($position !== null) {
343 8
            $pos = $bundle->jsOptions['position'] ?? null;
344
345 8
            if ($pos === null) {
346 8
                $bundle->jsOptions['position'] = $pos = $position;
347 2
            } elseif ($pos > $position) {
348 2
                throw new \RuntimeException("An asset bundle that depends on '$name' has a higher javascript file position configured than '$name'.");
349
            }
350
351
            // update position for all dependencies
352 8
            foreach ($bundle->depends as $dep) {
353 6
                $this->registerAssetBundle($dep, $pos);
354
            }
355
        }
356
357 11
        return $bundle;
358
    }
359
360
    /**
361
     * Registers a meta tag.
362
     *
363
     * For example, a description meta tag can be added like the following:
364
     *
365
     * ```php
366
     * $view->registerMetaTag([
367
     *     'name' => 'description',
368
     *     'content' => 'This website is about funny raccoons.'
369
     * ]);
370
     * ```
371
     *
372
     * will result in the meta tag `<meta name="description" content="This website is about funny raccoons.">`.
373
     *
374
     * @param array $options the HTML attributes for the meta tag.
375
     * @param string $key the key that identifies the meta tag. If two meta tags are registered with the same key, the
376
     * latter will overwrite the former. If this is null, the new meta tag will be appended to the
377
     * existing ones.
378
     *
379
     * @return void
380
     */
381
    public function registerMetaTag(array $options, string $key = null): void
382
    {
383
        if ($key === null) {
384
            $this->metaTags[] = Html::tag('meta', '', $options);
385
        } else {
386
            $this->metaTags[$key] = Html::tag('meta', '', $options);
387
        }
388
    }
389
390
    /**
391
     * Registers a link tag.
392
     *
393
     * For example, a link tag for a custom [favicon](http://www.w3.org/2005/10/howto-favicon) can be added like the
394
     * following:
395
     *
396
     * ```php
397
     * $view->registerLinkTag(['rel' => 'icon', 'type' => 'image/png', 'href' => '/myicon.png']);
398
     * ```
399
     *
400
     * which will result in the following HTML: `<link rel="icon" type="image/png" href="/myicon.png">`.
401
     *
402
     * **Note:** To register link tags for CSS stylesheets, use [[registerCssFile()]] instead, which has more options
403
     * for this kind of link tag.
404
     *
405
     * @param array $options the HTML attributes for the link tag.
406
     * @param string|null $key the key that identifies the link tag. If two link tags are registered with the same
407
     * key, the latter will overwrite the former. If this is null, the new link tag will be appended
408
     * to the existing ones.
409
     */
410
    public function registerLinkTag(array $options, ?string $key = null): void
411
    {
412
        if ($key === null) {
413
            $this->linkTags[] = Html::tag('link', '', $options);
414
        } else {
415
            $this->linkTags[$key] = Html::tag('link', '', $options);
416
        }
417
    }
418
419
    /**
420
     * Registers CSRF meta tags.
421
     *
422
     * They are rendered dynamically to retrieve a new CSRF token for each request.
423
     *
424
     * ```php
425
     * $view->registerCsrfMetaTags();
426
     * ```
427
     *
428
     * The above code will result in `<meta name="csrf-param" content="[Yiisoft\Web\Request::$csrfParam]">` and
429
     * `<meta name="csrf-token" content="tTNpWKpdy-bx8ZmIq9R72...K1y8IP3XGkzZA==">` added to the page.
430
     *
431
     * Note: Hidden CSRF input of ActiveForm will be automatically refreshed by calling `window.yii.refreshCsrfToken()`
432
     * from `yii.js`.
433
     */
434
    public function registerCsrfMetaTags(): void
435
    {
436
        $this->metaTags['csrf_meta_tags'] = $this->renderDynamic('return Yiisoft\Html\Html::csrfMetaTags();');
437
    }
438
439
    /**
440
     * Registers a CSS code block.
441
     *
442
     * @param string $css the content of the CSS code block to be registered
443
     * @param array $options the HTML attributes for the `<style>`-tag.
444
     * @param string $key the key that identifies the CSS code block. If null, it will use $css as the key. If two CSS
445
     * code blocks are registered with the same key, the latter will overwrite the former.
446
     */
447
    public function registerCss(string $css, array $options = [], string $key = null): void
448
    {
449
        $key = $key ?: md5($css);
450
        $this->css[$key] = Html::style($css, $options);
451
    }
452
453
    /**
454
     * Registers a CSS file.
455
     *
456
     * This method should be used for simple registration of CSS files. If you want to use features of
457
     * {@see AssetManager} like appending timestamps to the URL and file publishing options, use {@see AssetBundle}
458
     * and {@see registerAssetBundle()} instead.
459
     *
460
     * @param string $url the CSS file to be registered.
461
     * @param array $options the HTML attributes for the link tag. Please refer to {@see \Yiisoft\Html\Html::cssFile()}
462
     * for the supported options. The following options are specially handled and are not treated as HTML
463
     * attributes:
464
     *
465
     *   - `depends`: array, specifies the names of the asset bundles that this CSS file depends on.
466
     *
467
     * @param string $key the key that identifies the CSS script file. If null, it will use $url as the key. If two CSS
468
     * files are registered with the same key, the latter will overwrite the former.
469
     *
470
     * @return void
471
     */
472 18
    public function registerCssFile(string $url, array $options = [], string $key = null): void
473
    {
474 18
        $key = $key ?: $url;
475
476 18
        $depends = ArrayHelper::remove($options, 'depends', []);
477
478 18
        if (empty($depends)) {
479 18
            $this->cssFiles[$key] = Html::cssFile($url, $options);
480
        } else {
481
            $bundle = $this->createBundle([
482
                'baseUrl' => '',
483
                'css' => [strncmp($url, '//', 2) === 0 ? $url : ltrim($url, '/')],
484
                'cssOptions' => $options,
485
                'depends' => (array) $depends,
486
            ]);
487
            $bundles = [$key => $bundle];
0 ignored issues
show
Unused Code introduced by
The assignment to $bundles is dead and can be removed.
Loading history...
488
489
            $this->registerAssetBundle($key);
490
        }
491
    }
492
493
    /**
494
     * Registers a JS code block.
495
     *
496
     * @param string $js the JS code block to be registered
497
     * @param int $position the position at which the JS script tag should be inserted in a page.
498
     *
499
     * The possible values are:
500
     *
501
     * - [[POS_HEAD]]: in the head section
502
     * - [[POS_BEGIN]]: at the beginning of the body section
503
     * - [[POS_END]]: at the end of the body section. This is the default value.
504
     * - [[POS_LOAD]]: executed when HTML page is completely loaded.
505
     * - [[POS_READY]]: executed when HTML document composition is ready.
506
     *
507
     * @param string $key the key that identifies the JS code block. If null, it will use $js as the key. If two JS code
508
     * blocks are registered with the same key, the latter will overwrite the former.
509
     *
510
     * @return void
511
     */
512 1
    public function registerJs(string $js, int $position = self::POS_END, string $key = null): void
513
    {
514 1
        $key = $key ?: md5($js);
515 1
        $this->js[$position][$key] = $js;
516
    }
517
518
    /**
519
     * Registers a JS file.
520
     *
521
     * This method should be used for simple registration of JS files. If you want to use features of
522
     * {@see AssetManager} like appending timestamps to the URL and file publishing options, use {@see AssetBundle}
523
     * and {@see registerAssetBundle()} instead.
524
     *
525
     * @param string $url the JS file to be registered.
526
     * @param array $options the HTML attributes for the script tag. The following options are specially handled and
527
     * are not treated as HTML attributes:
528
     *
529
     * - `depends`: array, specifies the names of the asset bundles that this JS file depends on.
530
     * - `position`: specifies where the JS script tag should be inserted in a page. The possible values are:
531
     *     * [[POS_HEAD]]: in the head section
532
     *     * [[POS_BEGIN]]: at the beginning of the body section
533
     *     * [[POS_END]]: at the end of the body section. This is the default value.
534
     *
535
     * Please refer to {@see \Yiisoft\Html\Html::jsFile()} for other supported options.
536
     *
537
     * @param string $key the key that identifies the JS script file. If null, it will use $url as the key. If two JS
538
     * files are registered with the same key at the same position, the latter will overwrite the former.
539
     * Note that position option takes precedence, thus files registered with the same key, but different
540
     * position option will not override each other.
541
     *
542
     * @return void
543
     */
544 19
    public function registerJsFile(string $url, array $options = [], string $key = null): void
545
    {
546 19
        $key = $key ?: $url;
547
548 19
        $depends = ArrayHelper::remove($options, 'depends', []);
549
550 19
        if (empty($depends)) {
551 19
            $position = ArrayHelper::remove($options, 'position', self::POS_END);
552 19
            $this->jsFiles[$position][$key] = Html::jsFile($url, $options);
553
        } else {
554
            $bundle = $this->createBundle([
555
                'baseUrl' => '',
556
                'js' => [strncmp($url, '//', 2) === 0 ? $url : ltrim($url, '/')],
557
                'jsOptions' => $options,
558
                'depends' => (array) $depends,
559
            ]);
560
            $bundles = [$key => $bundle];
0 ignored issues
show
Unused Code introduced by
The assignment to $bundles is dead and can be removed.
Loading history...
561
            $this->registerAssetBundle($key);
562
        }
563
    }
564
565
    /**
566
     * Registers a JS code block defining a variable. The name of variable will be used as key, preventing duplicated
567
     * variable names.
568
     *
569
     * @param string $name Name of the variable
570
     * @param array|string $value Value of the variable
571
     * @param int $position the position in a page at which the JavaScript variable should be inserted.
572
     *
573
     * The possible values are:
574
     *
575
     * - [[POS_HEAD]]: in the head section. This is the default value.
576
     * - [[POS_BEGIN]]: at the beginning of the body section.
577
     * - [[POS_END]]: at the end of the body section.
578
     * - [[POS_LOAD]]: enclosed within jQuery(window).load().
579
     *   Note that by using this position, the method will automatically register the jQuery js file.
580
     * - [[POS_READY]]: enclosed within jQuery(document).ready().
581
     *   Note that by using this position, the method will automatically register the jQuery js file.
582
     */
583 1
    public function registerJsVar(string $name, $value, int $position = self::POS_HEAD): void
584
    {
585 1
        $js = sprintf('var %s = %s;', $name, \Yiisoft\Json\Json::htmlEncode($value));
586 1
        $this->registerJs($js, $position, $name);
587
    }
588
589
    /**
590
     * Renders the content to be inserted in the head section.
591
     *
592
     * The content is rendered using the registered meta tags, link tags, CSS/JS code blocks and files.
593
     *
594
     * @return string the rendered content
595
     */
596 32
    protected function renderHeadHtml(): string
597
    {
598 32
        $lines = [];
599 32
        if (!empty($this->metaTags)) {
600
            $lines[] = implode("\n", $this->metaTags);
601
        }
602
603 32
        if (!empty($this->linkTags)) {
604
            $lines[] = implode("\n", $this->linkTags);
605
        }
606 32
        if (!empty($this->cssFiles)) {
607 18
            $lines[] = implode("\n", $this->cssFiles);
608
        }
609 32
        if (!empty($this->css)) {
610
            $lines[] = implode("\n", $this->css);
611
        }
612 32
        if (!empty($this->jsFiles[self::POS_HEAD])) {
613 3
            $lines[] = implode("\n", $this->jsFiles[self::POS_HEAD]);
614
        }
615 32
        if (!empty($this->js[self::POS_HEAD])) {
616 1
            $lines[] = Html::script(implode("\n", $this->js[self::POS_HEAD]));
617
        }
618
619 32
        return empty($lines) ? '' : implode("\n", $lines);
620
    }
621
622
    /**
623
     * Renders the content to be inserted at the beginning of the body section.
624
     *
625
     * The content is rendered using the registered JS code blocks and files.
626
     *
627
     * @return string the rendered content
628
     */
629 32
    protected function renderBodyBeginHtml(): string
630
    {
631 32
        $lines = [];
632 32
        if (!empty($this->jsFiles[self::POS_BEGIN])) {
633 3
            $lines[] = implode("\n", $this->jsFiles[self::POS_BEGIN]);
634
        }
635 32
        if (!empty($this->js[self::POS_BEGIN])) {
636
            $lines[] = Html::script(implode("\n", $this->js[self::POS_BEGIN]));
637
        }
638
639 32
        return empty($lines) ? '' : implode("\n", $lines);
640
    }
641
642
    /**
643
     * Renders the content to be inserted at the end of the body section.
644
     *
645
     * The content is rendered using the registered JS code blocks and files.
646
     *
647
     * @param bool $ajaxMode whether the view is rendering in AJAX mode. If true, the JS scripts registered at
648
     * [[POS_READY]] and [[POS_LOAD]] positions will be rendered at the end of the view like normal scripts.
649
     *
650
     * @return string the rendered content
651
     */
652 32
    protected function renderBodyEndHtml(bool $ajaxMode): string
653
    {
654 32
        $lines = [];
655
656 32
        if (!empty($this->jsFiles[self::POS_END])) {
657 15
            $lines[] = implode("\n", $this->jsFiles[self::POS_END]);
658
        }
659
660 32
        if ($ajaxMode) {
661
            $scripts = [];
662
            if (!empty($this->js[self::POS_END])) {
663
                $scripts[] = implode("\n", $this->js[self::POS_END]);
664
            }
665
            if (!empty($this->js[self::POS_READY])) {
666
                $scripts[] = implode("\n", $this->js[self::POS_READY]);
667
            }
668
            if (!empty($this->js[self::POS_LOAD])) {
669
                $scripts[] = implode("\n", $this->js[self::POS_LOAD]);
670
            }
671
            if (!empty($scripts)) {
672
                $lines[] = Html::script(implode("\n", $scripts));
673
            }
674
        } else {
675 32
            if (!empty($this->js[self::POS_END])) {
676
                $lines[] = Html::script(implode("\n", $this->js[self::POS_END]));
677
            }
678 32
            if (!empty($this->js[self::POS_READY])) {
679
                $js = "document.addEventListener('DOMContentLoaded', function(event) {\n" . implode("\n", $this->js[self::POS_READY]) . "\n});";
680
                $lines[] = Html::script($js, ['type' => 'text/javascript']);
681
            }
682 32
            if (!empty($this->js[self::POS_LOAD])) {
683
                $js = "window.addEventListener('load', function (event) {\n" . implode("\n", $this->js[self::POS_LOAD]) . "\n});";
684
                $lines[] = Html::script($js, ['type' => 'text/javascript']);
685
            }
686
        }
687
688 32
        return empty($lines) ? '' : implode("\n", $lines);
689
    }
690
691
    /**
692
     * @param array $options
693
     *
694
     * @return AssetBundle
695
     */
696
    private function createBundle(array $options): AssetBundle
697
    {
698
        $bundle = new AssetBundle();
699
        $bundle->baseUrl = $options['baseUrl'];
700
        $bundle->js = $options['js'];
701
        $bundle->jsOptions = $options['jsOptions'];
702
        $bundle->depends = $options['depends'];
703
704
        return $bundle;
705
    }
706
}
707