Completed
Pull Request — master (#4242)
by Craig
04:51
created

JsResolver::validateBag()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 4
nc 3
nop 0
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Zikula package.
7
 *
8
 * Copyright Zikula - https://ziku.la/
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Zikula\ThemeModule\Engine\Asset;
15
16
use Zikula\ThemeModule\Engine\AssetBag;
17
18
/**
19
 * Class JsResolver
20
 *
21
 * This class compiles all js page assets into proper html code for inclusion into a page header or footer
22
 */
23
class JsResolver implements ResolverInterface
24
{
25
    /**
26
     * @var AssetBag
27
     */
28
    private $bag;
29
30
    /**
31
     * @var MergerInterface
32
     */
33
    private $merger;
34
35
    /**
36
     * @var bool
37
     */
38
    private $combine;
39
40
    public function __construct(
41
        string $env,
42
        AssetBag $bag,
43
        MergerInterface $merger,
44
        bool $combine = false
45
    ) {
46
        $this->bag = $bag;
47
        $this->merger = $merger;
48
        $this->combine = ('prod' === $env) && $combine;
49
    }
50
51
    public function compile(): string
52
    {
53
        $this->validateBag();
54
        $assets = $this->bag->allWithWeight();
55
        if ($this->combine) {
56
            $assets = $this->merger->merge($assets);
57
        }
58
        $scripts = '';
59
        foreach ($assets as $asset => $weight) {
60
            $scripts .= '<script src="' . $asset . '"></script>' . "\n";
61
        }
62
63
        return $scripts;
64
    }
65
66
    public function getBag(): AssetBag
67
    {
68
        return $this->bag;
69
    }
70
71
    private function validateBag(): void
72
    {
73
        foreach ($this->getBag()->all() as $source) {
74
            // if already there, add jquery-ui again to force weight setting is correct
75
            // jQueryUI must be loaded before Bootstrap, refs #3912
76
            if ('jquery-ui.min.js' === mb_substr($source, -16)
77
                || 'jquery-ui.js' === mb_substr($source, -12)
78
            ) {
79
                $this->bag->add([$source => AssetBag::WEIGHT_JQUERY_UI]);
80
            }
81
        }
82
    }
83
}
84