Completed
Pull Request — master (#303)
by Atlas
02:57
created

ConfigFileReaderJson::read()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 10
nc 4
nop 1
dl 0
loc 20
rs 9.2
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
     * ConfigFileReaderJson constructor.
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
        $jsonDataImploded = $this->collapseArray($jsonData);
44
45
        foreach ($jsonDataImploded as $key => $value) {
46
            $config->set($key, $value);
47
        }
48
    }
49
50
    /**
51
     * Collapses array into a one-dimensional one by imploding nested keys with '-'
52
     *
53
     * @param array $arr
54
     *
55
     * @return array
56
     */
57
    private function collapseArray(array $arr)
58
    {
59
        $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
60
        $result = [];
61
        foreach ($iterator as $leafValue) {
62
            $keys = [];
63
            foreach (range(0, $iterator->getDepth()) as $depth) {
64
                $keys[] = $iterator->getSubIterator($depth)->key();
65
            }
66
            $result[join('-', $keys)] = $leafValue;
67
        }
68
69
        return $result;
70
    }
71
}
72