Passed
Push — master ( 9601bc...40dd50 )
by Evgeniy
02:37
created

WebpackAssetExporter::__construct()   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 1
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\Exporter;
6
7
use RuntimeException;
8
use Yiisoft\Assets\AssetExporterInterface;
9
use Yiisoft\Assets\AssetUtil;
10
11
use function array_shift;
12
use function array_unique;
13
use function implode;
14
use function is_array;
15
16
/**
17
 * Exports the CSS and JavaScript file paths of asset bundles, converting them to `import '/path/to/file';`
18
 * expressions and placing them in the specified JavaScript file for later loading into Webpack.
19
 *
20
 * {@see https://webpack.js.org/concepts/#entry}
21
 */
22
final class WebpackAssetExporter implements AssetExporterInterface
23
{
24
    /**
25
     * @var string The full path to the target JavaScript file.
26
     */
27
    private string $targetFile;
28
29
    /**
30
     * @param string $targetFile The full path to the target JavaScript file.
31
     */
32 3
    public function __construct(string $targetFile)
33
    {
34 3
        $this->targetFile = $targetFile;
35 3
    }
36
37
    /**
38
     * {@inheritDoc}
39
     *
40
     * @throws RuntimeException If an error occurred while writing to the JavaScript file.
41
     */
42 3
    public function export(array $assetBundles): void
43
    {
44 3
        $imports = [];
45
46 3
        foreach ($assetBundles as $bundle) {
47 3
            if ($bundle->cdn || empty($bundle->sourcePath)) {
48 2
                continue;
49
            }
50
51 3
            foreach ($bundle->css as $css) {
52 3
                if ($css !== null) {
53 3
                    $file = is_array($css) ? array_shift($css) : $css;
54 3
                    $imports[] = "import '{$bundle->sourcePath}/{$file}';";
55
                }
56
            }
57
58 3
            foreach ($bundle->js as $js) {
59 3
                if ($js !== null) {
60 3
                    $file = is_array($js) ? array_shift($js) : $js;
61 3
                    $imports[] = "import '{$bundle->sourcePath}/{$file}';";
62
                }
63
            }
64
        }
65
66 3
        AssetUtil::exportToFile($this->targetFile, implode("\n", array_unique($imports)) . "\n");
67 2
    }
68
}
69