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

WebView::getAssetBundles()   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 0
Metric Value
eloc 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
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
     * Undocumented variable
92
     *
93
     * @var AssetManager $assetManager
94
     */
95
    private $assetManager;
96
97
    /**
98
     * @var string the page title
99
     */
100
    private $title;
0 ignored issues
show
introduced by
The private property $title is not used, and could be removed.
Loading history...
101
102
    /**
103
     * @var array the registered meta tags.
104
     *
105
     * {@see registerMetaTag()}
106
     */
107
    private $metaTags = [];
108
109
    /**
110
     * @var array the registered link tags.
111
     *
112
     * {@see registerLinkTag()}
113
     */
114
    private $linkTags = [];
115
116
    /**
117
     * @var array the registered CSS code blocks.
118
     *
119
     * {@see registerCss()}
120
     */
121
    private $css = [];
122
123
    /**
124
     * @var array the registered CSS files.
125
     *
126
     * {@see registerCssFile()}
127
     */
128
    private $cssFiles = [];
129
130
    /**
131
     * @var array the registered JS code blocks
132
     *
133
     * {@see registerJs()}
134
     */
135
    private $js = [];
136
137
    /**
138
     * @var array the registered JS files.
139
     *
140
     * {@see registerJsFile()}
141
     */
142
    private $jsFiles = [];
143
144
    /**
145
     * Marks the position of an HTML head section.
146
     */
147 31
    public function head(): void
148
    {
149 31
        echo self::PH_HEAD;
150
    }
151
152
    /**
153
     * Marks the beginning of an HTML body section.
154
     */
155 31
    public function beginBody(): void
156
    {
157 31
        echo self::PH_BODY_BEGIN;
158 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

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

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

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

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