Completed
Pull Request — master (#428)
by personal
01:37
created

ConfigFileReaderJson::read()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 10
nop 1
dl 0
loc 30
rs 8.8177
c 0
b 0
f 0
1
<?php
2
3
namespace Hal\Application\Config\File;
4
5
use Hal\Application\Config\Config;
6
use RecursiveArrayIterator;
7
use RecursiveIteratorIterator;
8
9
class ConfigFileReaderJson implements ConfigFileReaderInterface
10
{
11
    /**
12
     * @var string
13
     */
14
    private $filename;
15
16
    /**
17
     * @param string $filename
18
     */
19
    public function __construct($filename)
20
    {
21
        $this->filename = $filename;
22
    }
23
24
    /**
25
     * @param Config $config
26
     *
27
     * @return void
28
     */
29
    public function read(Config $config)
30
    {
31
        $jsonText = file_get_contents($this->filename);
32
33
        if (false === $jsonText) {
34
            throw new \InvalidArgumentException("Cannot read configuration file '{$this->filename}'");
35
        }
36
37
        $jsonData = json_decode($jsonText, true);
38
39
        if (false === $jsonData) {
40
            throw new \InvalidArgumentException("Bad json file '{$this->filename}'");
41
        }
42
43
        if (isset($jsonData['includes'])) {
44
            $config->set('files', $jsonData['includes']);
45
            unset($jsonData['includes']);
46
        }
47
48
        if (isset($jsonData['groups'])) {
49
            $config->set('groups', $jsonData['groups']);
50
            unset($jsonData['groups']);
51
        }
52
53
        $jsonDataImploded = $this->collapseArray($jsonData);
54
55
        foreach ($jsonDataImploded as $key => $value) {
56
            $config->set($key, $value);
57
        }
58
    }
59
60
    /**
61
     * Collapses array into a one-dimensional one by imploding nested keys with '-'
62
     *
63
     * @param array $arr
64
     *
65
     * @return array
66
     */
67
    private function collapseArray(array $arr)
68
    {
69
        $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
70
        $result = [];
71
        foreach ($iterator as $leafValue) {
72
            $keys = [];
73
            foreach (range(0, $iterator->getDepth()) as $depth) {
74
                $keys[] = $iterator->getSubIterator($depth)->key();
75
            }
76
            $result[implode('-', $keys)] = $leafValue;
77
        }
78
79
        return $result;
80
    }
81
}
82