ConfigTree   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 1
dl 0
loc 57
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A toArray() 0 4 1
A getSettingFromPath() 0 14 3
A withAnotherConfigTreeMergedIn() 0 6 1
A getSubtreeFromPath() 0 8 2
1
<?php
2
namespace ConfigTree\Tree;
3
4
use ConfigTree\Exception\ConfigTreeParamNotSet;
5
6
class ConfigTree
7
{
8
    /** @var array */
9
    private $rawConfigArray;
10
11
    public function __construct(array $configArray)
12
    {
13
        $this->rawConfigArray = $configArray;
14
    }
15
16
    public function toArray() : array
17
    {
18
        return $this->rawConfigArray;
19
    }
20
21
    /**
22
     * @throws ConfigTreeParamNotSet
23
     *
24
     * @return mixed
25
     */
26
    public function getSettingFromPath(string $pathToConfigSettingInTree)
27
    {
28
        $nodesInPathThroughTree = explode('/', $pathToConfigSettingInTree);
29
30
        $configArray = $this->rawConfigArray;
31
32
        foreach ($nodesInPathThroughTree as $nodeInTree) {
33
            if (!isset($configArray[$nodeInTree])) {
34
                throw ConfigTreeParamNotSet::constructWithSettingPath($pathToConfigSettingInTree);
35
            }
36
            $configArray = $configArray[$nodeInTree];
37
        }
38
        return $configArray;
39
    }
40
41
    /**
42
     * In $configC = $configA->withAnotherConfigTreeMergedIn($configB), duplicate settings in $configB override $configA
43
     */
44
    public function withAnotherConfigTreeMergedIn(ConfigTree $anotherConfigTree) : ConfigTree
45
    {
46
        $thisAsArray = $this->rawConfigArray;
47
        $otherAsArray = $anotherConfigTree->toArray();
48
        return new ConfigTree(array_replace_recursive($thisAsArray, $otherAsArray));
49
    }
50
51
    /**
52
     * @throws ConfigTreeParamNotSet
53
     */
54
    public function getSubtreeFromPath(string $pathToSubtree) : ConfigTree
55
    {
56
        $settingsAsArray = $this->getSettingFromPath($pathToSubtree);
57
        if (!is_array($settingsAsArray)) {
58
            throw ConfigTreeParamNotSet::constructWithSettingPath($pathToSubtree);
59
        }
60
        return new ConfigTree($settingsAsArray);
61
    }
62
}
63