PackageConfiguration::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 9
ccs 4
cts 5
cp 0.8
crap 2.032
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace CompoLab\Domain;
4
5
/**
6
 *
7
 * @property string $name
8
 * @property array  $source
9
 * @property string $version
10
 * @property array  $dist
11
 * @property array  $require
12
 * @property array  $autoload
13
 */
14
final class PackageConfiguration
15
{
16
    /** @var array */
17
    private $data = [];
18
19 7
    public function __construct(array $data)
20
    {
21 7
        $keys = array_keys($data);
22
23 7
        if (!in_array('name', $keys)) {
24
            throw new \RuntimeException('Malformed package configuration');
25
        }
26
27 7
        $this->data = $data;
28 7
    }
29
30
    public static function buildFromPath(string $path): self
31
    {
32
        if (!$json = file_get_contents($path)) {
33
            throw new \RuntimeException(sprintf('File "%s" is not readable'));
34
        }
35
36
        return self::buildFromJson($json);
37
    }
38
39
    public static function buildFromJson(string $json): self
40
    {
41
        if (!$data = json_decode($json, true)) {
42
            throw new \RuntimeException('Impossible to decode JSON string as array');
43
        }
44
45
        return new self($data);
46
    }
47
48 3
    public function _toArray(): array
49
    {
50 3
        return $this->data;
51
    }
52
53
    /**
54
     *
55
     * @param string $name
56
     * @return string|array
57
     */
58
    public function __get($name)
59
    {
60
        $name = str_replace('-', '_', $name);
61
62
        if (!isset($this->data[$name])) {
63
            throw new \RuntimeException(sprintf('The is no "%s" property in composer.json'));
64
        }
65
66
        return $this->data[$name];
67
    }
68
}
69