Passed
Pull Request — master (#80)
by Evgeniy
02:54
created

AssetManager   C

Complexity

Total Complexity 57

Size/Duplication

Total Lines 442
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 106
c 3
b 0
f 0
dl 0
loc 442
ccs 124
cts 124
cp 1
rs 5.04
wmc 57

21 Methods

Rating   Name   Duplication   Size   Complexity  
A getCssFiles() 0 3 1
A withPublisher() 0 5 1
A registerFiles() 0 9 2
A getJsStrings() 0 3 1
A registerAllAllowed() 0 9 3
A loadBundle() 0 23 6
A register() 0 11 4
A isRegisteredBundle() 0 3 1
A getJsFiles() 0 3 1
A getBundle() 0 10 2
A withLoader() 0 6 1
A getJsVars() 0 3 1
A isAllowedBundleDependencies() 0 9 4
A getCssStrings() 0 3 1
A export() 0 11 3
A getAssetUrl() 0 3 1
A publishBundle() 0 7 4
A withConverter() 0 5 1
A __construct() 0 10 1
C registerAssetBundle() 0 45 13
A checkAllowedBundleName() 0 13 5

How to fix   Complexity   

Complex Class

Complex classes like AssetManager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AssetManager, and based on these observations, apply Extract Interface, too.

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 in_array;
12
use function is_array;
13
14
/**
15
 * AssetManager manages asset bundle configuration and loading.
16
 *
17
 * @psalm-type CssFile = array{0:string,1?:int}&array
18
 * @psalm-type CssString = array{0:mixed,1?:int}&array
19
 * @psalm-type JsFile = array{0:string,1?:int}&array
20
 * @psalm-type JsString = array{0:mixed,1?:int}&array
21
 */
22
final class AssetManager
23
{
24
    /**
25
     * @var string[] List of names of allowed asset bundles. If the array is empty, then any asset bundles are allowed.
26
     */
27
    private array $allowedBundleNames;
28
29
    /**
30
     * @var array The asset bundle configurations. This property is provided to customize asset bundles.
31
     */
32
    private array $customizedBundles;
33
34
    /**
35
     * @var array AssetBundle[] list of the registered asset bundles.
36
     * The keys are the bundle names, and the values are the registered {@see AssetBundle} objects.
37
     *
38
     * {@see registerAssetBundle()}
39
     */
40
    private array $registeredBundles = [];
41
42
    private array $loadedBundles = [];
43
    private array $dummyBundles = [];
44
45
    private ?AssetPublisherInterface $publisher = null;
46
    private AssetLoaderInterface $loader;
47
    private AssetRegistrar $registrar;
48
49
    /**
50
     * @param Aliases $aliases The aliases instance.
51
     * @param AssetLoaderInterface $loader The loader instance.
52
     * @param string[] $allowedBundleNames List of names of allowed asset bundles. If the array is empty, then any
53
     * asset bundles are allowed. If the names of allowed asset bundles were specified, only these asset bundles
54
     * or their dependencies can be registered {@see register()} and obtained {@see getBundle()}. Also, specifying
55
     * names allows to export {@see export()} asset bundles automatically without first registering them manually.
56
     * @param array $customizedBundles The asset bundle configurations. Provided to customize asset bundles.
57
     * When a bundle is being loaded by {@see getBundle()}, if it has a corresponding configuration specified
58
     * here, the configuration will be applied to the bundle. The array keys are the asset class bundle names
59
     * (without leading backslash). If a value is false, it means the corresponding asset bundle is disabled
60
     * and {@see getBundle()} should return an instance of the specified asset bundle with empty property values.
61
     */
62 95
    public function __construct(
63
        Aliases $aliases,
64
        AssetLoaderInterface $loader,
65
        array $allowedBundleNames = [],
66
        array $customizedBundles = []
67
    ) {
68 95
        $this->loader = $loader;
69 95
        $this->allowedBundleNames = $allowedBundleNames;
70 95
        $this->customizedBundles = $customizedBundles;
71 95
        $this->registrar = new AssetRegistrar($aliases, $this->loader);
72 95
    }
73
74
    /**
75
     * Returns a cloned named asset bundle.
76
     *
77
     * This method will first look for the bundle in {@see $customizedBundles}.
78
     * If not found, it will treat `$name` as the class of the asset bundle and create a new instance of it.
79
     * If `$name` is not a class name, an {@see AssetBundle} instance will be created.
80
     *
81
     * Cloning is used to prevent an asset bundle instance from being modified in a non-context of the asset manager.
82
     *
83
     * @param string $name The class name of the asset bundle (without the leading backslash).
84
     *
85
     * @throws InvalidConfigException For invalid asset bundle configuration.
86
     *
87
     * @return AssetBundle The asset bundle instance.
88
     */
89 9
    public function getBundle(string $name): AssetBundle
90
    {
91 9
        if (!empty($this->allowedBundleNames)) {
92 4
            $this->checkAllowedBundleName($name);
93
        }
94
95 9
        $bundle = $this->loadBundle($name);
96 9
        $bundle = $this->publishBundle($bundle);
97
98 9
        return clone $bundle;
99
    }
100
101
    /**
102
     * Returns the actual URL for the specified asset.
103
     *
104
     * @param string $name The asset bundle name.
105
     * @param string $path The asset path.
106
     *
107
     * @throws InvalidConfigException If asset files are not found.
108
     *
109
     * @return string The actual URL for the specified asset.
110
     */
111 1
    public function getAssetUrl(string $name, string $path): string
112
    {
113 1
        return $this->loader->getAssetUrl($this->getBundle($name), $path);
114
    }
115
116
    /**
117
     * Return config array CSS AssetBundle.
118
     *
119
     * @psalm-return CssFile[]
120
     */
121 12
    public function getCssFiles(): array
122
    {
123 12
        return $this->registrar->getCssFiles();
124
    }
125
126
    /**
127
     * Returns CSS blocks.
128
     *
129
     * @return array
130
     * @psalm-return CssString[]
131
     */
132 2
    public function getCssStrings(): array
133
    {
134 2
        return $this->registrar->getCssStrings();
135
    }
136
137
    /**
138
     * Returns config array JS AssetBundle.
139
     *
140
     * @psalm-return JsFile[]
141
     */
142 22
    public function getJsFiles(): array
143
    {
144 22
        return $this->registrar->getJsFiles();
145
    }
146
147
    /**
148
     * Returns JS code blocks.
149
     *
150
     * @return array
151
     * @psalm-return JsString[]
152
     */
153 3
    public function getJsStrings(): array
154
    {
155 3
        return $this->registrar->getJsStrings();
156
    }
157
158
    /**
159
     * Returns JS variables.
160
     *
161
     * @return array
162
     */
163 3
    public function getJsVars(): array
164
    {
165 3
        return $this->registrar->getJsVars();
166
    }
167
168
    /**
169
     * Returns a new instance with the specified converter.
170
     *
171
     * @param AssetConverterInterface $converter
172
     *
173
     * @return self
174
     */
175 95
    public function withConverter(AssetConverterInterface $converter): self
176
    {
177 95
        $new = clone $this;
178 95
        $new->registrar = $new->registrar->withConverter($converter);
179 95
        return $new;
180
    }
181
182
    /**
183
     * Returns a new instance with the specified loader.
184
     *
185
     * @param AssetLoaderInterface $loader
186
     *
187
     * @return self
188
     */
189 5
    public function withLoader(AssetLoaderInterface $loader): self
190
    {
191 5
        $new = clone $this;
192 5
        $new->loader = $loader;
193 5
        $new->registrar = $new->registrar->withLoader($new->loader);
194 5
        return $new;
195
    }
196
197
    /**
198
     * Returns a new instance with the specified publisher.
199
     *
200
     * @param AssetPublisherInterface $publisher
201
     *
202
     * @return self
203
     */
204 95
    public function withPublisher(AssetPublisherInterface $publisher): self
205
    {
206 95
        $new = clone $this;
207 95
        $new->publisher = $publisher;
208 95
        return $new;
209
    }
210
211
    /**
212
     * Exports registered asset bundles.
213
     *
214
     * When using the allowed asset bundles, the export result will always be the same,
215
     * since the asset bundles are registered before the export. If do not use the allowed asset bundles mode,
216
     * must register {@see register()} all the required asset bundles before exporting.
217
     *
218
     * @param AssetExporterInterface $exporter The exporter instance.
219
     *
220
     * @throws InvalidConfigException If an error occurs during registration when using allowed asset bundles.
221
     * @throws RuntimeException If no asset bundles were registered or an error occurred during the export.
222
     */
223 8
    public function export(AssetExporterInterface $exporter): void
224
    {
225 8
        if (!empty($this->allowedBundleNames)) {
226 3
            $this->registerAllAllowed();
227
        }
228
229 8
        if (empty($this->registeredBundles)) {
230 1
            throw new RuntimeException('Not a single asset bundle was registered.');
231
        }
232
233 7
        $exporter->export($this->registeredBundles);
234 7
    }
235
236
    /**
237
     * Registers asset bundles by names.
238
     *
239
     * @param string[] $names
240
     *
241
     * @throws InvalidConfigException
242
     * @throws RuntimeException
243
     */
244 95
    public function register(array $names, ?int $jsPosition = null, ?int $cssPosition = null): void
245
    {
246 95
        if (!empty($this->allowedBundleNames)) {
247 3
            foreach ($names as $name) {
248 3
                $this->checkAllowedBundleName($name);
249
            }
250
        }
251
252 95
        foreach ($names as $name) {
253 60
            $this->registerAssetBundle($name, $jsPosition, $cssPosition);
254 54
            $this->registerFiles($name);
255
        }
256 95
    }
257
258
    /**
259
     * Registers all allowed asset bundles.
260
     *
261
     * @throws InvalidConfigException
262
     * @throws RuntimeException
263
     */
264 5
    public function registerAllAllowed(): void
265
    {
266 5
        if (empty($this->allowedBundleNames)) {
267 1
            throw new RuntimeException('The allowed names of the asset bundles were not set.');
268
        }
269
270 4
        foreach ($this->allowedBundleNames as $name) {
271 4
            $this->registerAssetBundle($name);
272 4
            $this->registerFiles($name);
273
        }
274 4
    }
275
276
    /**
277
     * Returns whether the asset bundle is registered.
278
     *
279
     * @param string $name The class name of the asset bundle (without the leading backslash).
280
     *
281
     * @return bool Whether the asset bundle is registered.
282
     */
283 4
    public function isRegisteredBundle(string $name): bool
284
    {
285 4
        return isset($this->registeredBundles[$name]);
286
    }
287
288
    /**
289
     * Registers the named asset bundle.
290
     *
291
     * All dependent asset bundles will be registered.
292
     *
293
     * @param string $name The class name of the asset bundle (without the leading backslash).
294
     * @param int|null $jsPosition If set, this forces a minimum position for javascript files.
295
     * This will adjust depending assets javascript file position or fail if requirement can not be met.
296
     * If this is null, asset bundles position settings will not be changed.
297
     *
298
     * {@see AssetRegistrar::registerJsFile()} For more details on javascript position.
299
     *
300
     * @throws InvalidConfigException If the asset or the asset file paths to be published does not exist.
301
     * @throws RuntimeException If the asset bundle does not exist or a circular dependency is detected.
302
     */
303 64
    private function registerAssetBundle(string $name, ?int $jsPosition = null, ?int $cssPosition = null): void
304
    {
305 64
        if (!isset($this->registeredBundles[$name])) {
306 64
            $bundle = $this->publishBundle($this->loadBundle($name));
307
308 63
            $this->registeredBundles[$name] = false;
309
310 63
            foreach ($bundle->depends as $dep) {
311 35
                $this->registerAssetBundle($dep, $bundle->jsPosition, $bundle->cssPosition);
312
            }
313
314 62
            unset($this->registeredBundles[$name]);
315 62
            $this->registeredBundles[$name] = $bundle;
316 14
        } elseif ($this->registeredBundles[$name] === false) {
317 1
            throw new RuntimeException("A circular dependency is detected for bundle \"{$name}\".");
318
        } else {
319 13
            $bundle = $this->registeredBundles[$name];
320
        }
321
322 62
        if ($jsPosition !== null || $cssPosition !== null) {
323 16
            if ($jsPosition !== null) {
324 12
                if ($bundle->jsPosition === null) {
325 11
                    $bundle->jsPosition = $jsPosition;
326 5
                } elseif ($bundle->jsPosition > $jsPosition) {
327 4
                    throw new RuntimeException(
328 4
                        "An asset bundle that depends on \"{$name}\" has a higher JavaScript file " .
329 4
                        "position configured than \"{$name}\"."
330
                    );
331
                }
332
            }
333
334 16
            if ($cssPosition !== null) {
335 5
                if ($bundle->cssPosition === null) {
336 1
                    $bundle->cssPosition = $cssPosition;
337 4
                } elseif ($bundle->cssPosition > $cssPosition) {
338 4
                    throw new RuntimeException(
339 4
                        "An asset bundle that depends on \"{$name}\" has a higher CSS file " .
340 4
                        "position configured than \"{$name}\"."
341
                    );
342
                }
343
            }
344
345
            // update position for all dependencies
346 12
            foreach ($bundle->depends as $dep) {
347 7
                $this->registerAssetBundle($dep, $bundle->jsPosition, $bundle->cssPosition);
348
            }
349
        }
350 60
    }
351
352
    /**
353
     * Register assets from a named bundle and its dependencies.
354
     *
355
     * @param string $bundleName The asset bundle name.
356
     *
357
     * @throws InvalidConfigException If asset files are not found.
358
     */
359 58
    private function registerFiles(string $bundleName): void
360
    {
361 58
        $bundle = $this->registeredBundles[$bundleName];
362
363 58
        foreach ($bundle->depends as $dep) {
364 28
            $this->registerFiles($dep);
365
        }
366
367 58
        $this->registrar->register($bundle);
368 45
    }
369
370
    /**
371
     * Loads an asset bundle class by name.
372
     *
373
     * @param string $name The asset bundle name.
374
     *
375
     * @throws InvalidConfigException For invalid asset bundle configuration.
376
     *
377
     * @return AssetBundle The asset bundle instance.
378
     */
379 67
    private function loadBundle(string $name): AssetBundle
380
    {
381 67
        if (isset($this->loadedBundles[$name])) {
382 8
            return $this->loadedBundles[$name];
383
        }
384
385 67
        if (!isset($this->customizedBundles[$name])) {
386 58
            return $this->loadedBundles[$name] = $this->loader->loadBundle($name);
387
        }
388
389 24
        if ($this->customizedBundles[$name] instanceof AssetBundle) {
390 1
            return $this->loadedBundles[$name] = $this->customizedBundles[$name];
391
        }
392
393 23
        if (is_array($this->customizedBundles[$name])) {
394 21
            return $this->loadedBundles[$name] = $this->loader->loadBundle($name, $this->customizedBundles[$name]);
395
        }
396
397 2
        if ($this->customizedBundles[$name] === false) {
398 1
            return $this->dummyBundles[$name] ??= $this->loader->loadBundle($name, (array) (new AssetBundle()));
399
        }
400
401 1
        throw new InvalidConfigException("Invalid configuration of the \"{$name}\" asset bundle.");
402
    }
403
404
    /**
405
     * Publishes a asset bundle.
406
     *
407
     * @param AssetBundle $bundle The asset bundle to publish.
408
     *
409
     * @throws InvalidConfigException If the asset or the asset file paths to be published does not exist.
410
     *
411
     * @return AssetBundle The published asset bundle.
412
     */
413 66
    private function publishBundle(AssetBundle $bundle): AssetBundle
414
    {
415 66
        if (!$bundle->cdn && $this->publisher !== null && !empty($bundle->sourcePath)) {
416 13
            [$bundle->basePath, $bundle->baseUrl] = $this->publisher->publish($bundle);
417
        }
418
419 66
        return $bundle;
420
    }
421
422
    /**
423
     * Checks whether asset bundle are allowed by name {@see $allowedBundleNames}.
424
     *
425
     * @param string $name The asset bundle name to check.
426
     *
427
     * @throws InvalidConfigException For invalid asset bundle configuration.
428
     * @throws RuntimeException If The asset bundle name is not allowed.
429
     */
430 4
    public function checkAllowedBundleName(string $name): void
431
    {
432 4
        if (isset($this->loadedBundles[$name]) || in_array($name, $this->allowedBundleNames, true)) {
433 4
            return;
434
        }
435
436 3
        foreach ($this->allowedBundleNames as $bundleName) {
437 3
            if ($this->isAllowedBundleDependencies($name, $this->loadBundle($bundleName))) {
438 1
                return;
439
            }
440
        }
441
442 3
        throw new RuntimeException("The \"{$name}\" asset bundle is not allowed.");
443
    }
444
445
    /**
446
     * Recursively checks whether the asset bundle name is allowed in dependencies.
447
     *
448
     * @param string $name The asset bundle name to check.
449
     * @param AssetBundle $bundle The asset bundle to check.
450
     *
451
     * @throws InvalidConfigException For invalid asset bundle configuration.
452
     *
453
     * @return bool Whether the asset bundle name is allowed in dependencies.
454
     */
455 3
    private function isAllowedBundleDependencies(string $name, AssetBundle $bundle): bool
456
    {
457 3
        foreach ($bundle->depends as $depend) {
458 2
            if ($name === $depend || $this->isAllowedBundleDependencies($name, $this->loadBundle($depend))) {
459 1
                return true;
460
            }
461
        }
462
463 3
        return false;
464
    }
465
}
466