Passed
Push — master ( 781931...9601bc )
by Alexander
02:28
created

AssetJsonExporter   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Test Coverage

Coverage 88.89%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 7
c 1
b 0
f 1
dl 0
loc 31
ccs 8
cts 9
cp 0.8889
rs 10
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A export() 0 10 4
A __construct() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Assets\Exporter;
6
7
use JsonException;
8
use RuntimeException;
9
use Yiisoft\Assets\AssetExporterInterface;
10
use Yiisoft\Json\Json;
11
12
use function dirname;
13
use function file_put_contents;
14
use function is_dir;
15
use function is_writable;
16
17
/**
18
 * Exports asset bundles with the values of all properties {@see AssetBundle::jsonSerialize()} to a JSON file.
19
 */
20
final class AssetJsonExporter implements AssetExporterInterface
21
{
22
    /**
23
     * @var string The full path to the target JSON file.
24
     */
25
    private string $targetFile;
26
27
    /**
28
     * @param string $targetFile The full path to the target JSON file.
29
     */
30 5
    public function __construct(string $targetFile)
31
    {
32 5
        $this->targetFile = $targetFile;
33 5
    }
34
35
    /**
36
     * {@inheritDoc}
37
     *
38
     * @throws JsonException If an error occurred during JSON encoding of asset bundles.
39
     * @throws RuntimeException If an error occurred while writing to the JSON file.
40
     */
41 4
    public function export(array $assetBundles): void
42
    {
43 4
        $targetDirectory = dirname($this->targetFile);
44
45 4
        if (!is_dir($targetDirectory) || !is_writable($targetDirectory)) {
46 1
            throw new RuntimeException("Target directory \"{$targetDirectory}\" does not exist or is not writable.");
47
        }
48
49 3
        if (file_put_contents($this->targetFile, Json::encode($assetBundles), LOCK_EX) === false) {
50
            throw new RuntimeException("An error occurred while writing to the \"{$this->targetFile}\" file.");
51
        }
52 3
    }
53
}
54