Passed
Push — master ( 7525e3...97ef2a )
by Alexander
13:01 queued 11:22
created

AssetManager::getJsFiles()   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
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
ccs 2
cts 2
cp 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Assets;
6
7
use Psr\Log\LoggerInterface;
8
use Yiisoft\Assets\Exception\InvalidConfigException;
9
10
/**
11
 * AssetManager manages asset bundle configuration and loading.
12
 */
13
final class AssetManager
14
{
15
    /**
16
     * @var array AssetBundle[] list of the registered asset bundles. The keys are the bundle names, and the values
17
     * are the registered {@see AssetBundle} objects.
18
     *
19
     * {@see registerAssetBundle()}
20
     */
21
    private array $assetBundles = [];
22
23
    private AssetConverterInterface $converter;
24
    private AssetPublisher $publisher;
25
26
    /**
27
     * @var array list of asset bundle configurations. This property is provided to customize asset bundles.
28
     * When a bundle is being loaded by {@see getBundle()}, if it has a corresponding configuration specified here, the
29
     * configuration will be applied to the bundle.
30
     *
31
     * The array keys are the asset bundle names, which typically are asset bundle class names without leading
32
     * backslash. The array values are the corresponding configurations. If a value is false, it means the corresponding
33
     * asset bundle is disabled and {@see getBundle()} should return null.
34
     *
35
     * If this property is false, it means the whole asset bundle feature is disabled and {@see {getBundle()} will
36
     * always return null.
37
     */
38
    private array $bundles = [];
39
40
    /**
41
     * @var array the registered CSS files.
42
     *
43
     * {@see registerCssFile()}
44
     */
45
    private array $cssFiles = [];
46
47
    /**
48
     * @var array $dummyBundles
49
     */
50
    private array $dummyBundles;
51
52
    /**
53
     * @var array the registered JS files.
54
     *
55
     * {@see registerJsFile()}
56
     */
57
    private array $jsFiles = [];
58
59
    /**
60
     * @var LoggerInterface $logger
61
     */
62
    private LoggerInterface $logger;
63
64 59
    public function __construct(LoggerInterface $logger)
65
    {
66 59
        $this->logger = $logger;
67 59
    }
68
69
    /**
70
     * Registers the asset manager being used by this view object.
71
     *
72
     * @return array the asset manager. Defaults to the "assetManager" application component.
73
     */
74 25
    public function getAssetBundles(): array
75
    {
76 25
        return $this->assetBundles;
77
    }
78
79
    /**
80
     * Returns the named asset bundle.
81
     *
82
     * This method will first look for the bundle in {@see bundles()}. If not found, it will treat `$name` as the class
83
     * of the asset bundle and create a new instance of it.
84
     *
85
     * @param string $name the class name of the asset bundle (without the leading backslash).
86
     *
87
     * @return AssetBundle the asset bundle instance
88
     *
89
     * @throws InvalidConfigException
90
     */
91 30
    public function getBundle(string $name): AssetBundle
92
    {
93 30
        if (!isset($this->bundles[$name])) {
94 26
            return $this->bundles[$name] = $this->publisher->loadBundle($name, []);
95
        }
96
97 15
        if ($this->bundles[$name] instanceof AssetBundle) {
98
            return $this->bundles[$name];
99
        }
100
101 15
        if (\is_array($this->bundles[$name])) {
102 15
            return $this->bundles[$name] = $this->publisher->loadBundle($name, $this->bundles[$name]);
103
        }
104
105
        if ($this->bundles[$name] === false) {
106
            return $this->loadDummyBundle($name);
107
        }
108
109
        throw new InvalidConfigException("Invalid asset bundle configuration: $name");
110
    }
111
112 1
    public function getConverter(): AssetConverterInterface
113
    {
114 1
        return $this->converter;
115
    }
116
117
    /**
118
     * Return config array CSS AssetBundle.
119
     *
120
     * @return array
121
     */
122 15
    public function getCssFiles(): array
123
    {
124 15
        return $this->cssFiles;
125
    }
126
127
    /**
128
     * Return config array JS AssetBundle.
129
     *
130
     * @return array
131
     */
132 24
    public function getJsFiles(): array
133
    {
134 24
        return $this->jsFiles;
135
    }
136
137 7
    public function getPublisher(): AssetPublisherInterface
138
    {
139 7
        return $this->publisher;
140
    }
141
142
    /**
143
     * This property is provided to customize asset bundles.
144
     *
145
     * @param array $value
146
     *
147
     * @return void
148
     *
149
     * {@see bundles}
150
     */
151 15
    public function setBundles(array $value): void
152
    {
153 15
        $this->bundles = $value;
154 15
    }
155
156
    /**
157
     * AssetConverter component.
158
     *
159
     * @param AssetConverterInterface $value the asset converter. This can be eitheran object implementing the
160
     * {@see AssetConverterInterface}, or a configuration array that can be used to create the asset converter object.
161
     */
162 59
    public function setConverter(AssetConverterInterface $value): void
163
    {
164 59
        $this->converter = $value;
165 59
    }
166
167
    /**
168
     * AssetPublisher component.
169
     *
170
     * @param AssetPublisher $value
171
     *
172
     * @return void
173
     *
174
     * {@see publisher}
175
     */
176 59
    public function setPublisher(AssetPublisherInterface $value): void
177
    {
178 59
        $this->publisher = $value;
179 59
    }
180
181
    /**
182
     * Generate the array configuration of the AssetBundles
183
     *
184
     * @param array $names
185
     * @param integer|null $position
186
     *
187
     * @return void
188
     */
189 28
    public function register(array $names, ?int $position = null): void
190
    {
191 28
        foreach ($names as $name) {
192 28
            $this->registerAssetBundle($name, $position);
193 23
            $this->registerFiles($name);
194
        }
195 20
    }
196
197
    /**
198
     * Registers a CSS file.
199
     *
200
     * This method should be used for simple registration of CSS files. If you want to use features of
201
     * {@see AssetManager} like appending timestamps to the URL and file publishing options, use {@see AssetBundle}
202
     * and {@see registerAssetBundle()} instead.
203
     *
204
     * @param string $url the CSS file to be registered.
205
     * @param array $options the HTML attributes for the link tag.
206
     *
207
     * @return void
208
     */
209 26
    public function registerCssFile(string $url, array $options = [], string $key = null): void
210
    {
211 26
        $key = $key ?: $url;
212
213 26
        $this->cssFiles[$key]['url'] = $url;
214 26
        $this->cssFiles[$key]['attributes'] = $options;
215 26
    }
216
217
    /**
218
     * Registers a JS file.
219
     *
220
     * This method should be used for simple registration of JS files. If you want to use features of
221
     * {@see AssetManager} like appending timestamps to the URL and file publishing options, use {@see AssetBundle}
222
     * and {@see registerAssetBundle()} instead.
223
     *
224
     * @param string $url the JS file to be registered.
225
     * @param array $options the HTML attributes for the script tag. The following options are specially handled and
226
     * are not treated as HTML attributes:
227
     *
228
     * - `position`: specifies where the JS script tag should be inserted in a page. The possible values are:
229
     *     * {@see \Yiisoft\View\WebView::POSITION_HEAD} in the head section
230
     *     * {@see \Yiisoft\View\WebView::POSITION_BEGIN} at the beginning of the body section
231
     *     * {@see \Yiisoft\View\WebView::POSITION_END} at the end of the body section. This is the default value.
232
     *
233
     * @return void
234
     */
235 32
    public function registerJsFile(string $url, array $options = [], string $key = null): void
236
    {
237 32
        $key = $key ?: $url;
238
239 32
        if (!\array_key_exists('position', $options)) {
240 26
            $options = array_merge(['position' => 3], $options);
241
        }
242
243 32
        $this->jsFiles[$key]['url'] = $url;
244 32
        $this->jsFiles[$key]['attributes'] = $options;
245 32
    }
246
247
    /**
248
     * Converter SASS, SCSS, Stylus and other formats to CSS.
249
     *
250
     * @param AssetBundle $bundle
251
     *
252
     * @return AssetBundle
253
     */
254 23
    private function convertCss(AssetBundle $bundle): AssetBundle
255
    {
256 23
        foreach ($bundle->css as $i => $css) {
257 16
            if (\is_array($css)) {
258 1
                $file = \array_shift($css);
259 1
                if (AssetUtil::isRelative($file)) {
260 1
                    $css = \array_merge($bundle->cssOptions, $css);
261
262 1
                    if (is_file("$bundle->basePath/$file")) {
263
                        \array_unshift($css, $this->converter->convert(
264
                            $file,
265
                            $bundle->basePath,
0 ignored issues
show
Bug introduced by
It seems like $bundle->basePath can also be of type null; however, parameter $basePath of Yiisoft\Assets\AssetConverterInterface::convert() 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

265
                            /** @scrutinizer ignore-type */ $bundle->basePath,
Loading history...
266
                            $bundle->converterOptions
267
                        ));
268
269 1
                        $bundle->css[$i] = $css;
270
                    }
271
                }
272 16
            } elseif (AssetUtil::isRelative($css)) {
273 16
                if (is_file("$bundle->basePath/$css")) {
274 6
                    $bundle->css[$i] = $this->converter->convert(
275 6
                        $css,
276 6
                        $bundle->basePath,
277 6
                        $bundle->converterOptions
278
                    );
279
                }
280
            }
281
        }
282
283 23
        return $bundle;
284
    }
285
286
    /**
287
     * Convert files CoffeScript, TypeScript and other formats to JavaScript.
288
     *
289
     * @param AssetBundle $bundle
290
     *
291
     * @return AssetBundle
292
     */
293 23
    private function convertJs(AssetBundle $bundle): AssetBundle
294
    {
295 23
        foreach ($bundle->js as $i => $js) {
296 23
            if (\is_array($js)) {
297 2
                $file = \array_shift($js);
298 2
                if (AssetUtil::isRelative($file)) {
299 1
                    $js = \array_merge($bundle->jsOptions, $js);
300
301 1
                    if (is_file("$bundle->basePath/$file")) {
302
                        \array_unshift($js, $this->converter->convert(
303
                            $file,
304
                            $bundle->basePath,
0 ignored issues
show
Bug introduced by
It seems like $bundle->basePath can also be of type null; however, parameter $basePath of Yiisoft\Assets\AssetConverterInterface::convert() 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

304
                            /** @scrutinizer ignore-type */ $bundle->basePath,
Loading history...
305
                            $bundle->converterOptions
306
                        ));
307
308 2
                        $bundle->js[$i] = $js;
309
                    }
310
                }
311 22
            } elseif (AssetUtil::isRelative($js)) {
312 22
                if (is_file("$bundle->basePath/$js")) {
313 6
                    $bundle->js[$i] = $this->converter->convert($js, $bundle->basePath);
314
                }
315
            }
316
        }
317
318 23
        return $bundle;
319
    }
320
321
    /**
322
     * Registers the named asset bundle.
323
     *
324
     * All dependent asset bundles will be registered.
325
     *
326
     * @param string $name the class name of the asset bundle (without the leading backslash)
327
     * @param int|null $position if set, this forces a minimum position for javascript files. This will adjust depending
328
     * assets javascript file position or fail if requirement can not be met. If this is null, asset
329
     * bundles position settings will not be changed.
330
     *
331
     * {@see registerJsFile()} for more details on javascript position.
332
     *
333
     * @return AssetBundle the registered asset bundle instance
334
     * @throws InvalidConfigException
335
     *
336
     * @throws \RuntimeException if the asset bundle does not exist or a circular dependency is detected
337
     */
338 28
    private function registerAssetBundle(string $name, ?int $position = null): AssetBundle
339
    {
340 28
        if (!isset($this->assetBundles[$name])) {
341 28
            $bundle = $this->getBundle($name);
342
343 26
            $this->assetBundles[$name] = false;
344
345
            // register dependencies
346 26
            $pos = $bundle->jsOptions['position'] ?? null;
347
348 26
            foreach ($bundle->depends as $dep) {
349 21
                $this->registerAssetBundle($dep, $pos);
350
            }
351
352 25
            $this->assetBundles[$name] = $bundle;
353 10
        } elseif ($this->assetBundles[$name] === false) {
354 1
            throw new \RuntimeException("A circular dependency is detected for bundle '$name'.");
355
        } else {
356 9
            $bundle = $this->assetBundles[$name];
357
        }
358
359 25
        if ($position !== null) {
360 11
            $pos = $bundle->jsOptions['position'] ?? null;
361
362 11
            if ($pos === null) {
363 10
                $bundle->jsOptions['position'] = $pos = $position;
364 5
            } elseif ($pos > $position) {
365 4
                throw new \RuntimeException(
366 4
                    "An asset bundle that depends on '$name' has a higher javascript file " .
367 4
                    "position configured than '$name'."
368
                );
369
            }
370
371
            // update position for all dependencies
372 11
            foreach ($bundle->depends as $dep) {
373 7
                $this->registerAssetBundle($dep, $pos);
374
            }
375
        }
376 25
        return $bundle;
377
    }
378
379
    /**
380
     * Loads dummy bundle by name.
381
     *
382
     * @param string $bundleName AssetBunle name
383
     *
384
     * @return AssetBundle
385
     * @throws InvalidConfigException
386
     */
387
    private function loadDummyBundle(string $bundleName): AssetBundle
388
    {
389
        if (!isset($this->dummyBundles[$bundleName])) {
390
            $this->dummyBundles[$bundleName] = $this->publisher->loadBundle($bundleName, [
391
                'sourcePath' => null,
392
                'js' => [],
393
                'css' => [],
394
                'depends' => [],
395
            ]);
396
        }
397
398
        return $this->dummyBundles[$bundleName];
399
    }
400
401
    /**
402
     * Register assets from a named bundle and its dependencies
403
     *
404
     * @param string $bundleName
405
     *
406
     * @return void
407
     */
408 23
    private function registerFiles(string $bundleName): void
409
    {
410 23
        if (!isset($this->assetBundles[$bundleName])) {
411
            return;
412
        }
413
414 23
        $bundle = $this->assetBundles[$bundleName];
415
416 23
        foreach ($bundle->depends as $dep) {
417 18
            $this->registerFiles($dep);
418
        }
419
420 23
        $this->registerAssetFiles($bundle);
421 22
    }
422
423
    /**
424
     * Registers asset files from a bundle considering dependencies
425
     */
426 23
    private function registerAssetFiles(AssetBundle $bundle): void
427
    {
428 23
        if (isset($bundle->basePath, $bundle->baseUrl) && !empty($this->converter)) {
429 23
            $this->convertCss($bundle);
430 23
            $this->convertJs($bundle);
431
        }
432
433 23
        foreach ($bundle->js as $js) {
434 23
            if (\is_array($js)) {
435 2
                $file = array_shift($js);
436 2
                $options = array_merge($bundle->jsOptions, $js);
437 2
                $this->registerJsFile($this->publisher->getAssetUrl($bundle, $file), $options);
438 22
            } elseif ($js !== null) {
439 22
                $this->registerJsFile($this->publisher->getAssetUrl($bundle, $js), $bundle->jsOptions);
440
            }
441
        }
442
443 22
        foreach ($bundle->css as $css) {
444 16
            if (\is_array($css)) {
445 1
                $file = array_shift($css);
446 1
                $options = array_merge($bundle->cssOptions, $css);
447 1
                $this->registerCssFile($this->publisher->getAssetUrl($bundle, $file), $options);
448 16
            } elseif ($css !== null) {
449 16
                $this->registerCssFile($this->publisher->getAssetUrl($bundle, $css), $bundle->cssOptions);
450
            }
451
        }
452 22
    }
453
}
454