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
|
|
|
|