Passed
Pull Request — master (#50)
by Alexander
02:52
created

WebView::setAssetManager()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 1
b 0
f 0
cc 1
nc 1
nop 1
crap 1
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 31
    public function head(): void
146
    {
147 31
        echo self::PH_HEAD;
148
    }
149
150
    /**
151
     * Marks the beginning of an HTML body section.
152
     */
153 31
    public function beginBody(): void
154
    {
155 31
        echo self::PH_BODY_BEGIN;
156 31
        $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 31
    public function endBody(): void
163
    {
164 31
        $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 31
        echo self::PH_BODY_END;
166
167 31
        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 31
    public function endPage($ajaxMode = false): void
180
    {
181 31
        $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 31
        $content = ob_get_clean();
184
185 31
        echo strtr($content, [
186 31
            self::PH_HEAD => $this->renderHeadHtml(),
187 31
            self::PH_BODY_BEGIN => $this->renderBodyBeginHtml(),
188 31
            self::PH_BODY_END => $this->renderBodyEndHtml($ajaxMode),
189
        ]);
190
191 31
        $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 51
    public function setAssetManager(AssetManager $value): void
257
    {
258 51
        $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 31
    public function clear(): void
267
    {
268 31
        $this->metaTags = [];
269 31
        $this->linkTags = [];
270 31
        $this->css = [];
271 31
        $this->cssFiles = [];
272 31
        $this->js = [];
273 31
        $this->jsFiles = [];
274 31
        $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
            $am = $this->getAssetManager();
324 12
            $bundle = $am->getBundle($name);
325
326 12
            $this->assetBundles[$name] = false;
327
328
            // register dependencies
329
330 12
            $pos = isset($bundle->jsOptions['position']) ? $bundle->jsOptions['position'] : null;
331
332 12
            foreach ($bundle->depends as $dep) {
333 10
                $this->registerAssetBundle($dep, $pos);
334
            }
335
336 11
            $this->assetBundles[$name] = $bundle;
337 8
        } elseif ($this->assetBundles[$name] === false) {
0 ignored issues
show
introduced by
The condition $this->assetBundles[$name] === false is always false.
Loading history...
338 1
            throw new \RuntimeException("A circular dependency is detected for bundle '$name'.");
339
        } else {
340 7
            $bundle = $this->assetBundles[$name];
341
        }
342
343 11
        if ($position !== null) {
344 8
            $pos = isset($bundle->jsOptions['position']) ? $bundle->jsOptions['position'] : null;
345
346 8
            if ($pos === null) {
347 8
                $bundle->jsOptions['position'] = $pos = $position;
348 2
            } elseif ($pos > $position) {
349 2
                throw new \RuntimeException("An asset bundle that depends on '$name' has a higher javascript file position configured than '$name'.");
350
            }
351
352
            // update position for all dependencies
353 8
            foreach ($bundle->depends as $dep) {
354 6
                $this->registerAssetBundle($dep, $pos);
355
            }
356
        }
357
358 11
        return $bundle;
359
    }
360
361
    /**
362
     * Registers a meta tag.
363
     *
364
     * For example, a description meta tag can be added like the following:
365
     *
366
     * ```php
367
     * $view->registerMetaTag([
368
     *     'name' => 'description',
369
     *     'content' => 'This website is about funny raccoons.'
370
     * ]);
371
     * ```
372
     *
373
     * will result in the meta tag `<meta name="description" content="This website is about funny raccoons.">`.
374
     *
375
     * @param array $options the HTML attributes for the meta tag.
376
     * @param string $key the key that identifies the meta tag. If two meta tags are registered with the same key, the
377
     * latter will overwrite the former. If this is null, the new meta tag will be appended to the
378
     * existing ones.
379
     *
380
     * @return void
381
     */
382
    public function registerMetaTag(array $options, string $key = null): void
383
    {
384
        if ($key === null) {
385
            $this->metaTags[] = Html::tag('meta', '', $options);
386
        } else {
387
            $this->metaTags[$key] = Html::tag('meta', '', $options);
388
        }
389
    }
390
391
    /**
392
     * Registers a link tag.
393
     *
394
     * For example, a link tag for a custom [favicon](http://www.w3.org/2005/10/howto-favicon) can be added like the
395
     * following:
396
     *
397
     * ```php
398
     * $view->registerLinkTag(['rel' => 'icon', 'type' => 'image/png', 'href' => '/myicon.png']);
399
     * ```
400
     *
401
     * which will result in the following HTML: `<link rel="icon" type="image/png" href="/myicon.png">`.
402
     *
403
     * **Note:** To register link tags for CSS stylesheets, use [[registerCssFile()]] instead, which has more options
404
     * for this kind of link tag.
405
     *
406
     * @param array $options the HTML attributes for the link tag.
407
     * @param string|null $key the key that identifies the link tag. If two link tags are registered with the same
408
     * key, the latter will overwrite the former. If this is null, the new link tag will be appended
409
     * to the existing ones.
410
     */
411
    public function registerLinkTag(array $options, ?string $key = null): void
412
    {
413
        if ($key === null) {
414
            $this->linkTags[] = Html::tag('link', '', $options);
415
        } else {
416
            $this->linkTags[$key] = Html::tag('link', '', $options);
417
        }
418
    }
419
420
    /**
421
     * Registers CSRF meta tags.
422
     *
423
     * They are rendered dynamically to retrieve a new CSRF token for each request.
424
     *
425
     * ```php
426
     * $view->registerCsrfMetaTags();
427
     * ```
428
     *
429
     * The above code will result in `<meta name="csrf-param" content="[Yiisoft\Web\Request::$csrfParam]">` and
430
     * `<meta name="csrf-token" content="tTNpWKpdy-bx8ZmIq9R72...K1y8IP3XGkzZA==">` added to the page.
431
     *
432
     * Note: Hidden CSRF input of ActiveForm will be automatically refreshed by calling `window.yii.refreshCsrfToken()`
433
     * from `yii.js`.
434
     */
435
    public function registerCsrfMetaTags(): void
436
    {
437
        $this->metaTags['csrf_meta_tags'] = $this->renderDynamic('return Yiisoft\Html\Html::csrfMetaTags();');
438
    }
439
440
    /**
441
     * Registers a CSS code block.
442
     *
443
     * @param string $css the content of the CSS code block to be registered
444
     * @param array $options the HTML attributes for the `<style>`-tag.
445
     * @param string $key the key that identifies the CSS code block. If null, it will use $css as the key. If two CSS
446
     * code blocks are registered with the same key, the latter will overwrite the former.
447
     */
448
    public function registerCss(string $css, array $options = [], string $key = null): void
449
    {
450
        $key = $key ?: md5($css);
451
        $this->css[$key] = Html::style($css, $options);
452
    }
453
454
    /**
455
     * Registers a CSS file.
456
     *
457
     * This method should be used for simple registration of CSS files. If you want to use features of
458
     * {@see AssetManager} like appending timestamps to the URL and file publishing options, use {@see AssetBundle}
459
     * and {@see registerAssetBundle()} instead.
460
     *
461
     * @param string $url the CSS file to be registered.
462
     * @param array $options the HTML attributes for the link tag. Please refer to {@see \Yiisoft\Html\Html::cssFile()}
463
     * for the supported options. The following options are specially handled and are not treated as HTML
464
     * attributes:
465
     *
466
     *   - `depends`: array, specifies the names of the asset bundles that this CSS file depends on.
467
     *
468
     * @param string $key the key that identifies the CSS script file. If null, it will use $url as the key. If two CSS
469
     * files are registered with the same key, the latter will overwrite the former.
470
     *
471
     * @return void
472
     */
473 18
    public function registerCssFile(string $url, array $options = [], string $key = null): void
474
    {
475 18
        $key = $key ?: $url;
476
477 18
        $depends = ArrayHelper::remove($options, 'depends', []);
478
479 18
        if (empty($depends)) {
480 18
            $this->cssFiles[$key] = Html::cssFile($url, $options);
481
        } else {
482
            $bundle = $this->createBundle([
483
                'baseUrl' => '',
484
                'css' => [strncmp($url, '//', 2) === 0 ? $url : ltrim($url, '/')],
485
                'cssOptions' => $options,
486
                'depends' => (array) $depends,
487
            ]);
488
            $bundles = [$key => $bundle];
0 ignored issues
show
Unused Code introduced by
The assignment to $bundles is dead and can be removed.
Loading history...
489
490
            $this->registerAssetBundle($key);
491
        }
492
    }
493
494
    /**
495
     * Registers a JS code block.
496
     *
497
     * @param string $js the JS code block to be registered
498
     * @param int $position the position at which the JS script tag should be inserted in a page.
499
     *
500
     * The possible values are:
501
     *
502
     * - [[POS_HEAD]]: in the head section
503
     * - [[POS_BEGIN]]: at the beginning of the body section
504
     * - [[POS_END]]: at the end of the body section. This is the default value.
505
     * - [[POS_LOAD]]: executed when HTML page is completely loaded.
506
     * - [[POS_READY]]: executed when HTML document composition is ready.
507
     *
508
     * @param string $key the key that identifies the JS code block. If null, it will use $js as the key. If two JS code
509
     * blocks are registered with the same key, the latter will overwrite the former.
510
     *
511
     * @return void
512
     */
513 1
    public function registerJs(string $js, int $position = self::POS_END, string $key = null): void
514
    {
515 1
        $key = $key ?: md5($js);
516 1
        $this->js[$position][$key] = $js;
517
    }
518
519
    /**
520
     * Registers a JS file.
521
     *
522
     * This method should be used for simple registration of JS files. If you want to use features of
523
     * {@see AssetManager} like appending timestamps to the URL and file publishing options, use {@see AssetBundle}
524
     * and {@see registerAssetBundle()} instead.
525
     *
526
     * @param string $url the JS file to be registered.
527
     * @param array $options the HTML attributes for the script tag. The following options are specially handled and
528
     * are not treated as HTML attributes:
529
     *
530
     * - `depends`: array, specifies the names of the asset bundles that this JS file depends on.
531
     * - `position`: specifies where the JS script tag should be inserted in a page. The possible values are:
532
     *     * [[POS_HEAD]]: in the head section
533
     *     * [[POS_BEGIN]]: at the beginning of the body section
534
     *     * [[POS_END]]: at the end of the body section. This is the default value.
535
     *
536
     * Please refer to {@see \Yiisoft\Html\Html::jsFile()} for other supported options.
537
     *
538
     * @param string $key the key that identifies the JS script file. If null, it will use $url as the key. If two JS
539
     * files are registered with the same key at the same position, the latter will overwrite the former.
540
     * Note that position option takes precedence, thus files registered with the same key, but different
541
     * position option will not override each other.
542
     *
543
     * @return void
544
     */
545 19
    public function registerJsFile(string $url, array $options = [], string $key = null): void
546
    {
547 19
        $key = $key ?: $url;
548
549 19
        $depends = ArrayHelper::remove($options, 'depends', []);
550
551 19
        if (empty($depends)) {
552 19
            $position = ArrayHelper::remove($options, 'position', self::POS_END);
553 19
            $this->jsFiles[$position][$key] = Html::jsFile($url, $options);
554
        } else {
555
            $bundle = $this->createBundle([
556
                'baseUrl' => '',
557
                'js' => [strncmp($url, '//', 2) === 0 ? $url : ltrim($url, '/')],
558
                'jsOptions' => $options,
559
                'depends' => (array) $depends,
560
            ]);
561
            $bundles = [$key => $bundle];
0 ignored issues
show
Unused Code introduced by
The assignment to $bundles is dead and can be removed.
Loading history...
562
            $this->registerAssetBundle($key);
563
        }
564
    }
565
566
    /**
567
     * Registers a JS code block defining a variable. The name of variable will be used as key, preventing duplicated
568
     * variable names.
569
     *
570
     * @param string $name Name of the variable
571
     * @param array|string $value Value of the variable
572
     * @param int $position the position in a page at which the JavaScript variable should be inserted.
573
     *
574
     * The possible values are:
575
     *
576
     * - [[POS_HEAD]]: in the head section. This is the default value.
577
     * - [[POS_BEGIN]]: at the beginning of the body section.
578
     * - [[POS_END]]: at the end of the body section.
579
     * - [[POS_LOAD]]: enclosed within jQuery(window).load().
580
     *   Note that by using this position, the method will automatically register the jQuery js file.
581
     * - [[POS_READY]]: enclosed within jQuery(document).ready().
582
     *   Note that by using this position, the method will automatically register the jQuery js file.
583
     */
584 1
    public function registerJsVar(string $name, $value, int $position = self::POS_HEAD): void
585
    {
586 1
        $js = sprintf('var %s = %s;', $name, \Yiisoft\Json\Json::htmlEncode($value));
587 1
        $this->registerJs($js, $position, $name);
588
    }
589
590
    /**
591
     * Renders the content to be inserted in the head section.
592
     *
593
     * The content is rendered using the registered meta tags, link tags, CSS/JS code blocks and files.
594
     *
595
     * @return string the rendered content
596
     */
597 31
    protected function renderHeadHtml(): string
598
    {
599 31
        $lines = [];
600 31
        if (!empty($this->metaTags)) {
601
            $lines[] = implode("\n", $this->metaTags);
602
        }
603
604 31
        if (!empty($this->linkTags)) {
605
            $lines[] = implode("\n", $this->linkTags);
606
        }
607 31
        if (!empty($this->cssFiles)) {
608 18
            $lines[] = implode("\n", $this->cssFiles);
609
        }
610 31
        if (!empty($this->css)) {
611
            $lines[] = implode("\n", $this->css);
612
        }
613 31
        if (!empty($this->jsFiles[self::POS_HEAD])) {
614 3
            $lines[] = implode("\n", $this->jsFiles[self::POS_HEAD]);
615
        }
616 31
        if (!empty($this->js[self::POS_HEAD])) {
617 1
            $lines[] = Html::script(implode("\n", $this->js[self::POS_HEAD]));
618
        }
619
620 31
        return empty($lines) ? '' : implode("\n", $lines);
621
    }
622
623
    /**
624
     * Renders the content to be inserted at the beginning of the body section.
625
     *
626
     * The content is rendered using the registered JS code blocks and files.
627
     *
628
     * @return string the rendered content
629
     */
630 31
    protected function renderBodyBeginHtml(): string
631
    {
632 31
        $lines = [];
633 31
        if (!empty($this->jsFiles[self::POS_BEGIN])) {
634 3
            $lines[] = implode("\n", $this->jsFiles[self::POS_BEGIN]);
635
        }
636 31
        if (!empty($this->js[self::POS_BEGIN])) {
637
            $lines[] = Html::script(implode("\n", $this->js[self::POS_BEGIN]));
638
        }
639
640 31
        return empty($lines) ? '' : implode("\n", $lines);
641
    }
642
643
    /**
644
     * Renders the content to be inserted at the end of the body section.
645
     *
646
     * The content is rendered using the registered JS code blocks and files.
647
     *
648
     * @param bool $ajaxMode whether the view is rendering in AJAX mode. If true, the JS scripts registered at
649
     * [[POS_READY]] and [[POS_LOAD]] positions will be rendered at the end of the view like normal scripts.
650
     *
651
     * @return string the rendered content
652
     */
653 31
    protected function renderBodyEndHtml(bool $ajaxMode): string
654
    {
655 31
        $lines = [];
656
657 31
        if (!empty($this->jsFiles[self::POS_END])) {
658 15
            $lines[] = implode("\n", $this->jsFiles[self::POS_END]);
659
        }
660
661 31
        if ($ajaxMode) {
662
            $scripts = [];
663
            if (!empty($this->js[self::POS_END])) {
664
                $scripts[] = implode("\n", $this->js[self::POS_END]);
665
            }
666
            if (!empty($this->js[self::POS_READY])) {
667
                $scripts[] = implode("\n", $this->js[self::POS_READY]);
668
            }
669
            if (!empty($this->js[self::POS_LOAD])) {
670
                $scripts[] = implode("\n", $this->js[self::POS_LOAD]);
671
            }
672
            if (!empty($scripts)) {
673
                $lines[] = Html::script(implode("\n", $scripts));
674
            }
675
        } else {
676 31
            if (!empty($this->js[self::POS_END])) {
677
                $lines[] = Html::script(implode("\n", $this->js[self::POS_END]));
678
            }
679 31
            if (!empty($this->js[self::POS_READY])) {
680
                $js = "document.addEventListener('DOMContentLoaded', function(event) {\n" . implode("\n", $this->js[self::POS_READY]) . "\n});";
681
                $lines[] = Html::script($js, ['type' => 'text/javascript']);
682
            }
683 31
            if (!empty($this->js[self::POS_LOAD])) {
684
                $js = "window.addEventListener('load', function (event) {\n" . implode("\n", $this->js[self::POS_LOAD]) . "\n});";
685
                $lines[] = Html::script($js, ['type' => 'text/javascript']);
686
            }
687
        }
688
689 31
        return empty($lines) ? '' : implode("\n", $lines);
690
    }
691
692
    /**
693
     * @param array $options
694
     *
695
     * @return AssetBundle
696
     */
697
    private function createBundle(array $options): AssetBundle
698
    {
699
        $bundle = new AssetBundle();
700
        $bundle->baseUrl = $options['baseUrl'];
701
        $bundle->js = $options['js'];
702
        $bundle->jsOptions = $options['jsOptions'];
703
        $bundle->depends = $options['depends'];
704
705
        return $bundle;
706
    }
707
}
708