Passed
Pull Request — master (#68)
by Sergei
02:31
created

AssetManager::getJsVars()   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
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Assets;
6
7
use RuntimeException;
8
use Yiisoft\Aliases\Aliases;
9
use Yiisoft\Assets\Exception\InvalidConfigException;
10
11
use function array_key_exists;
12
use function array_merge;
13
use function array_shift;
14
use function array_unshift;
15
use function in_array;
16
use function is_array;
17
use function is_file;
18
use function is_int;
19
20
/**
21
 * AssetManager manages asset bundle configuration and loading.
22
 */
23
final class AssetManager
24
{
25
    /**
26
     * @var string[] List of names of allowed asset bundles. If the array is empty, then any asset bundles are allowed.
27
     */
28
    private array $allowedBundleNames;
29
30
    /**
31
     * @var array The asset bundle configurations. This property is provided to customize asset bundles.
32
     */
33
    private array $customizedBundles;
34
35
    /**
36
     * @var array AssetBundle[] list of the registered asset bundles.
37
     * The keys are the bundle names, and the values are the registered {@see AssetBundle} objects.
38
     *
39
     * {@see registerAssetBundle()}
40
     */
41
    private array $registeredBundles = [];
42
43
    private array $loadedBundles = [];
44
    private array $dummyBundles = [];
45
    private array $cssFiles = [];
46
    private array $jsFiles = [];
47
    private array $jsStrings = [];
48
    private array $jsVars = [];
49
    private ?AssetConverterInterface $converter = null;
50
    private ?AssetPublisherInterface $publisher = null;
51
    private AssetLoaderInterface $loader;
52
    private Aliases $aliases;
53
54
    /**
55
     * @param Aliases $aliases The aliases instance.
56
     * @param AssetLoaderInterface $loader The loader instance.
57
     * @param string[] $allowedBundleNames List of names of allowed asset bundles. If the array is empty, then any
58
     * asset bundles are allowed. If the names of allowed asset bundles were specified, only these asset bundles
59
     * or their dependencies can be registered {@see register()} and obtained {@see getBundle()}. Also, specifying
60
     * names allows to export {@see export()} asset bundles automatically without first registering them manually.
61
     * @param array $customizedBundles The asset bundle configurations. Provided to customize asset bundles.
62
     * When a bundle is being loaded by {@see getBundle()}, if it has a corresponding configuration specified
63
     * here, the configuration will be applied to the bundle. The array keys are the asset class bundle names
64
     * (without leading backslash). If a value is false, it means the corresponding asset bundle is disabled
65
     * and {@see getBundle()} should return an instance of the specified asset bundle with empty property values.
66
     */
67 90
    public function __construct(
68
        Aliases $aliases,
69
        AssetLoaderInterface $loader,
70
        array $allowedBundleNames = [],
71
        array $customizedBundles = []
72
    ) {
73 90
        $this->aliases = $aliases;
74 90
        $this->loader = $loader;
75 90
        $this->allowedBundleNames = $allowedBundleNames;
76 90
        $this->customizedBundles = $customizedBundles;
77 90
    }
78
79
    /**
80
     * Returns a cloned named asset bundle.
81
     *
82
     * This method will first look for the bundle in {@see $customizedBundles}.
83
     * If not found, it will treat `$name` as the class of the asset bundle and create a new instance of it.
84
     * If `$name` is not a class name, an {@see AssetBundle} instance will be created.
85
     *
86
     * Cloning is used to prevent an asset bundle instance from being modified in a non-context of the asset manager.
87
     *
88
     * @param string $name The class name of the asset bundle (without the leading backslash).
89
     *
90
     * @throws InvalidConfigException For invalid asset bundle configuration.
91
     *
92
     * @return AssetBundle The asset bundle instance.
93
     */
94 9
    public function getBundle(string $name): AssetBundle
95
    {
96 9
        if (!empty($this->allowedBundleNames)) {
97 4
            $this->checkAllowedBundleName($name);
98
        }
99
100 9
        $bundle = $this->loadBundle($name);
101 9
        $bundle = $this->publishBundle($bundle);
102
103 9
        return clone $bundle;
104
    }
105
106
    /**
107
     * Returns the actual URL for the specified asset.
108
     *
109
     * @param string $name The asset bundle name.
110
     * @param string $path The asset path.
111
     *
112
     * @throws InvalidConfigException If asset files are not found.
113
     *
114
     * @return string The actual URL for the specified asset.
115
     */
116 1
    public function getAssetUrl(string $name, string $path): string
117
    {
118 1
        return $this->loader->getAssetUrl($this->getBundle($name), $path);
119
    }
120
121
    /**
122
     * Return config array CSS AssetBundle.
123
     *
124
     * @return array
125
     */
126 16
    public function getCssFiles(): array
127
    {
128 16
        return $this->cssFiles;
129
    }
130
131
    /**
132
     * Returns config array JS AssetBundle.
133
     *
134
     * @return array
135
     */
136 26
    public function getJsFiles(): array
137
    {
138 26
        return $this->jsFiles;
139
    }
140
141
    /**
142
     * Returns JS code blocks.
143
     *
144
     * @return array
145
     */
146 1
    public function getJsStrings(): array
147
    {
148 1
        return $this->jsStrings;
149
    }
150
151
    /**
152
     * Returns JS variables.
153
     *
154
     * @return array
155
     */
156 1
    public function getJsVars(): array
157
    {
158 1
        return $this->jsVars;
159
    }
160
161
    /**
162
     * Returns a new instance with the specified converter.
163
     *
164
     * @param AssetConverterInterface $converter
165
     *
166
     * @return self
167
     */
168 90
    public function withConverter(AssetConverterInterface $converter): self
169
    {
170 90
        $new = clone $this;
171 90
        $new->converter = $converter;
172 90
        return $new;
173
    }
174
175
    /**
176
     * Returns a new instance with the specified loader.
177
     *
178
     * @param AssetLoaderInterface $loader
179
     *
180
     * @return self
181
     */
182 25
    public function withLoader(AssetLoaderInterface $loader): self
183
    {
184 25
        $new = clone $this;
185 25
        $new->loader = $loader;
186 25
        return $new;
187
    }
188
189
    /**
190
     * Returns a new instance with the specified publisher.
191
     *
192
     * @param AssetPublisherInterface $publisher
193
     *
194
     * @return self
195
     */
196 90
    public function withPublisher(AssetPublisherInterface $publisher): self
197
    {
198 90
        $new = clone $this;
199 90
        $new->publisher = $publisher;
200 90
        return $new;
201
    }
202
203
    /**
204
     * Exports registered asset bundles.
205
     *
206
     * When using the allowed asset bundles, the export result will always be the same,
207
     * since the asset bundles are registered before the export. If do not use the allowed asset bundles mode,
208
     * must register {@see register()} all the required asset bundles before exporting.
209
     *
210
     * @param AssetExporterInterface $exporter The exporter instance.
211
     *
212
     * @throws InvalidConfigException If an error occurs during registration when using allowed asset bundles.
213
     * @throws RuntimeException If no asset bundles were registered or an error occurred during the export.
214
     */
215 8
    public function export(AssetExporterInterface $exporter): void
216
    {
217 8
        if (!empty($this->allowedBundleNames)) {
218 3
            $this->registerAllAllowed();
219
        }
220
221 8
        if (empty($this->registeredBundles)) {
222 1
            throw new RuntimeException('Not a single asset bundle was registered.');
223
        }
224
225 7
        $exporter->export($this->registeredBundles);
226 7
    }
227
228
    /**
229
     * Registers asset bundles by names.
230
     *
231
     * @param string[] $names
232
     * @param int|null $position
233
     *
234
     * @throws InvalidConfigException
235
     * @throws RuntimeException
236
     */
237 90
    public function register(array $names, ?int $position = null): void
238
    {
239 90
        if (!empty($this->allowedBundleNames)) {
240 3
            foreach ($names as $name) {
241 3
                $this->checkAllowedBundleName($name);
242
            }
243
        }
244
245 90
        foreach ($names as $name) {
246 40
            $this->registerAssetBundle($name, $position);
247 36
            $this->registerFiles($name);
248
        }
249 90
    }
250
251
    /**
252
     * Registers all allowed asset bundles.
253
     *
254
     * @throws InvalidConfigException
255
     * @throws RuntimeException
256
     */
257 5
    public function registerAllAllowed(): void
258
    {
259 5
        if (empty($this->allowedBundleNames)) {
260 1
            throw new RuntimeException('The allowed names of the asset bundles were not set.');
261
        }
262
263 4
        foreach ($this->allowedBundleNames as $name) {
264 4
            $this->registerAssetBundle($name);
265 4
            $this->registerFiles($name);
266
        }
267 4
    }
268
269
    /**
270
     * Returns whether the asset bundle is registered.
271
     *
272
     * @param string $name The class name of the asset bundle (without the leading backslash).
273
     *
274
     * @return bool Whether the asset bundle is registered.
275
     */
276 4
    public function isRegisteredBundle(string $name): bool
277
    {
278 4
        return isset($this->registeredBundles[$name]);
279
    }
280
281
    /**
282
     * Registers a CSS file.
283
     *
284
     * @param string $url The CSS file to be registered.
285
     * @param array $options The HTML attributes for the link tag.
286
     * @param string|null $key The key that identifies the CSS file.
287
     */
288 35
    private function registerCssFile(string $url, array $options = [], string $key = null): void
289
    {
290 35
        $key = $key ?: $url;
291
292 35
        $this->cssFiles[$key]['url'] = $url;
293 35
        $this->cssFiles[$key]['attributes'] = $options;
294 35
    }
295
296
    /**
297
     * Registers a JS file.
298
     *
299
     * @param string $url The JS file to be registered.
300
     * @param array $options The HTML attributes for the script tag. The following options are specially handled and
301
     * are not treated as HTML attributes:
302
     *
303
     * - `position`: specifies where the JS script tag should be inserted in a page. The possible values are:
304
     *     * {@see \Yiisoft\View\WebView::POSITION_HEAD} In the head section.
305
     *     * {@see \Yiisoft\View\WebView::POSITION_BEGIN} At the beginning of the body section.
306
     *     * {@see \Yiisoft\View\WebView::POSITION_END} At the end of the body section. This is the default value.
307
     * @param string|null $key The key that identifies the JS file.
308
     */
309 45
    private function registerJsFile(string $url, array $options = [], string $key = null): void
310
    {
311 45
        $key = $key ?: $url;
312
313 45
        if (!array_key_exists('position', $options)) {
314 39
            $options = array_merge(['position' => 3], $options);
315
        }
316
317 45
        $this->jsFiles[$key]['url'] = $url;
318 45
        $this->jsFiles[$key]['attributes'] = $options;
319 45
    }
320
321
    /**
322
     * Converter SASS, SCSS, Stylus and other formats to CSS.
323
     *
324
     * @param AssetBundle $bundle
325
     */
326 15
    private function convertCss(AssetBundle $bundle): void
327
    {
328 15
        foreach ($bundle->css as $i => $css) {
329 14
            if (is_array($css)) {
330 1
                $file = array_shift($css);
331 1
                if (AssetUtil::isRelative($file)) {
332 1
                    $css = array_merge($bundle->cssOptions, $css);
333 1
                    $baseFile = $this->aliases->get("{$bundle->basePath}/{$file}");
334 1
                    if (is_file($baseFile)) {
335
                        /**
336
                         * @psalm-suppress PossiblyNullArgument
337
                         * @psalm-suppress PossiblyNullReference
338
                         */
339 1
                        array_unshift($css, $this->converter->convert(
0 ignored issues
show
Bug introduced by
The method convert() does not exist on null. ( Ignorable by Annotation )

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

339
                        array_unshift($css, $this->converter->/** @scrutinizer ignore-call */ convert(

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...
340 1
                            $file,
341 1
                            $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

341
                            /** @scrutinizer ignore-type */ $bundle->basePath,
Loading history...
342 1
                            $bundle->converterOptions,
343
                        ));
344
345 1
                        $bundle->css[$i] = $css;
346
                    }
347
                }
348 14
            } elseif (AssetUtil::isRelative($css)) {
349 14
                $baseCss = $this->aliases->get("{$bundle->basePath}/{$css}");
350 14
                if (is_file("$baseCss")) {
351
                    /**
352
                     * @psalm-suppress PossiblyNullArgument
353
                     * @psalm-suppress PossiblyNullReference
354
                     */
355 13
                    $bundle->css[$i] = $this->converter->convert(
356 13
                        $css,
357 13
                        $bundle->basePath,
358 13
                        $bundle->converterOptions
359
                    );
360
                }
361
            }
362
        }
363 15
    }
364
365
    /**
366
     * Convert files from TypeScript and other formats into JavaScript.
367
     *
368
     * @param AssetBundle $bundle
369
     */
370 15
    private function convertJs(AssetBundle $bundle): void
371
    {
372 15
        foreach ($bundle->js as $i => $js) {
373 15
            if (is_array($js)) {
374 2
                $file = array_shift($js);
375 2
                if (AssetUtil::isRelative($file)) {
376 2
                    $js = array_merge($bundle->jsOptions, $js);
377 2
                    $baseFile = $this->aliases->get("{$bundle->basePath}/{$file}");
378 2
                    if (is_file($baseFile)) {
379
                        /**
380
                         * @psalm-suppress PossiblyNullArgument
381
                         * @psalm-suppress PossiblyNullReference
382
                         */
383 2
                        array_unshift($js, $this->converter->convert(
384 2
                            $file,
385 2
                            $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

385
                            /** @scrutinizer ignore-type */ $bundle->basePath,
Loading history...
386 2
                            $bundle->converterOptions
387
                        ));
388
389 2
                        $bundle->js[$i] = $js;
390
                    }
391
                }
392 15
            } elseif (AssetUtil::isRelative($js)) {
393 15
                $baseJs = $this->aliases->get("{$bundle->basePath}/{$js}");
394 15
                if (is_file($baseJs)) {
395
                    /**
396
                     * @psalm-suppress PossiblyNullArgument
397
                     * @psalm-suppress PossiblyNullReference
398
                     */
399 14
                    $bundle->js[$i] = $this->converter->convert($js, $bundle->basePath);
400
                }
401
            }
402
        }
403 15
    }
404
405
    /**
406
     * Registers the named asset bundle.
407
     *
408
     * All dependent asset bundles will be registered.
409
     *
410
     * @param string $name The class name of the asset bundle (without the leading backslash).
411
     * @param int|null $position If set, this forces a minimum position for javascript files.
412
     * This will adjust depending assets javascript file position or fail if requirement can not be met.
413
     * If this is null, asset bundles position settings will not be changed.
414
     *
415
     * {@see registerJsFile()} For more details on javascript position.
416
     *
417
     * @throws InvalidConfigException If the asset or the asset file paths to be published does not exist.
418
     * @throws RuntimeException If the asset bundle does not exist or a circular dependency is detected.
419
     */
420 44
    private function registerAssetBundle(string $name, int $position = null): void
421
    {
422 44
        if (!isset($this->registeredBundles[$name])) {
423 44
            $bundle = $this->publishBundle($this->loadBundle($name));
424
425 43
            $this->registeredBundles[$name] = false;
426
427 43
            $pos = $bundle->jsOptions['position'] ?? null;
428
429 43
            foreach ($bundle->depends as $dep) {
430 31
                $this->registerAssetBundle($dep, $pos);
431
            }
432
433 42
            unset($this->registeredBundles[$name]);
434 42
            $this->registeredBundles[$name] = $bundle;
435 12
        } elseif ($this->registeredBundles[$name] === false) {
436 1
            throw new RuntimeException("A circular dependency is detected for bundle \"{$name}\".");
437
        } else {
438 11
            $bundle = $this->registeredBundles[$name];
439
        }
440
441 42
        if ($position !== null) {
442 11
            $pos = $bundle->jsOptions['position'] ?? null;
443
444 11
            if ($pos === null) {
445 10
                $bundle->jsOptions['position'] = $pos = $position;
446 5
            } elseif ($pos > $position) {
447 4
                throw new RuntimeException(
448 4
                    "An asset bundle that depends on \"{$name}\" has a higher JavaScript file " .
449 4
                    "position configured than \"{$name}\"."
450
                );
451
            }
452
453
            // update position for all dependencies
454 11
            foreach ($bundle->depends as $dep) {
455 7
                $this->registerAssetBundle($dep, $pos);
456
            }
457
        }
458 42
    }
459
460
    /**
461
     * Register assets from a named bundle and its dependencies.
462
     *
463
     * @param string $bundleName The asset bundle name.
464
     *
465
     * @throws InvalidConfigException If asset files are not found.
466
     */
467 40
    private function registerFiles(string $bundleName): void
468
    {
469 40
        if (!isset($this->registeredBundles[$bundleName])) {
470
            return;
471
        }
472
473 40
        $bundle = $this->registeredBundles[$bundleName];
474
475 40
        foreach ($bundle->depends as $dep) {
476 28
            $this->registerFiles($dep);
477
        }
478
479 40
        $this->registerAssetFiles($bundle);
480 37
    }
481
482
    /**
483
     * Registers asset files from a bundle considering dependencies.
484
     *
485
     * @param AssetBundle $bundle
486
     *
487
     * @throws InvalidConfigException If asset files are not found.
488
     */
489 40
    private function registerAssetFiles(AssetBundle $bundle): void
490
    {
491 40
        if (isset($bundle->basePath, $bundle->baseUrl) && null !== $this->converter) {
492 15
            $this->convertCss($bundle);
493 15
            $this->convertJs($bundle);
494
        }
495
496 40
        foreach ($bundle->js as $js) {
497 38
            if (is_array($js)) {
498 3
                $file = array_shift($js);
499 3
                $options = array_merge($bundle->jsOptions, $js);
500 3
                $this->registerJsFile($this->loader->getAssetUrl($bundle, $file), $options);
501 37
            } elseif ($js !== null) {
502 37
                $this->registerJsFile($this->loader->getAssetUrl($bundle, $js), $bundle->jsOptions);
503
            }
504
        }
505
506 37
        $this->jsStrings = array_merge($this->jsStrings, $bundle->jsStrings);
507 37
        $this->jsVars = array_merge($this->jsVars, $bundle->jsVars);
508
509 37
        foreach ($bundle->css as $css) {
510 25
            if (is_array($css)) {
511 1
                $file = array_shift($css);
512 1
                $options = array_merge($bundle->cssOptions, $css);
513 1
                $this->registerCssFile($this->loader->getAssetUrl($bundle, $file), $options);
514 25
            } elseif ($css !== null) {
515 25
                $this->registerCssFile($this->loader->getAssetUrl($bundle, $css), $bundle->cssOptions);
516
            }
517
        }
518 37
    }
519
520
    /**
521
     * Loads an asset bundle class by name.
522
     *
523
     * @param string $name The asset bundle name.
524
     *
525
     * @throws InvalidConfigException For invalid asset bundle configuration.
526
     *
527
     * @return AssetBundle The asset bundle instance.
528
     */
529 47
    private function loadBundle(string $name): AssetBundle
530
    {
531 47
        if (isset($this->loadedBundles[$name])) {
532 8
            return $this->loadedBundles[$name];
533
        }
534
535 47
        if (!isset($this->customizedBundles[$name])) {
536 42
            return $this->loadedBundles[$name] = $this->loader->loadBundle($name);
537
        }
538
539 20
        if ($this->customizedBundles[$name] instanceof AssetBundle) {
540 1
            return $this->loadedBundles[$name] = $this->customizedBundles[$name];
541
        }
542
543 19
        if (is_array($this->customizedBundles[$name])) {
544 17
            return $this->loadedBundles[$name] = $this->loader->loadBundle($name, $this->customizedBundles[$name]);
545
        }
546
547 2
        if ($this->customizedBundles[$name] === false) {
548 1
            return $this->dummyBundles[$name] ??= $this->loader->loadBundle($name, (array) (new AssetBundle()));
549
        }
550
551 1
        throw new InvalidConfigException("Invalid configuration of the \"{$name}\" asset bundle.");
552
    }
553
554
    /**
555
     * Publishes a asset bundle.
556
     *
557
     * @param AssetBundle $bundle The asset bundle to publish.
558
     *
559
     * @throws InvalidConfigException If the asset or the asset file paths to be published does not exist.
560
     *
561
     * @return AssetBundle The published asset bundle.
562
     */
563 46
    private function publishBundle(AssetBundle $bundle): AssetBundle
564
    {
565 46
        if (!$bundle->cdn && $this->publisher !== null && !empty($bundle->sourcePath)) {
566 13
            [$bundle->basePath, $bundle->baseUrl] = $this->publisher->publish($bundle);
567
        }
568
569 46
        return $bundle;
570
    }
571
572
    /**
573
     * Checks whether asset bundle are allowed by name {@see $allowedBundleNames}.
574
     *
575
     * @param string $name The asset bundle name to check.
576
     *
577
     * @throws InvalidConfigException For invalid asset bundle configuration.
578
     * @throws RuntimeException If The asset bundle name is not allowed.
579
     */
580 4
    public function checkAllowedBundleName(string $name): void
581
    {
582 4
        if (isset($this->loadedBundles[$name]) || in_array($name, $this->allowedBundleNames, true)) {
583 4
            return;
584
        }
585
586 3
        foreach ($this->allowedBundleNames as $bundleName) {
587 3
            if ($this->isAllowedBundleDependencies($name, $this->loadBundle($bundleName))) {
588 1
                return;
589
            }
590
        }
591
592 3
        throw new RuntimeException("The \"{$name}\" asset bundle is not allowed.");
593
    }
594
595
    /**
596
     * Recursively checks whether the asset bundle name is allowed in dependencies.
597
     *
598
     * @param string $name The asset bundle name to check.
599
     * @param AssetBundle $bundle The asset bundle to check.
600
     *
601
     * @throws InvalidConfigException For invalid asset bundle configuration.
602
     *
603
     * @return bool Whether the asset bundle name is allowed in dependencies.
604
     */
605 3
    private function isAllowedBundleDependencies(string $name, AssetBundle $bundle): bool
606
    {
607 3
        foreach ($bundle->depends as $depend) {
608 2
            if ($name === $depend || $this->isAllowedBundleDependencies($name, $this->loadBundle($depend))) {
609 1
                return true;
610
            }
611
        }
612
613 3
        return false;
614
    }
615
}
616