|
1
|
|
|
<?php |
|
2
|
|
|
namespace CloudFramework\Tool; |
|
3
|
|
|
|
|
4
|
|
|
use CloudFramework\Patterns\Singleton; |
|
5
|
|
|
|
|
6
|
|
|
/** |
|
7
|
|
|
* Class ConfigLoader |
|
8
|
|
|
* @package CloudFramework\Core |
|
9
|
|
|
*/ |
|
10
|
|
|
class ConfigLoader extends Singleton |
|
11
|
|
|
{ |
|
12
|
|
|
private $config = array(); |
|
13
|
|
|
|
|
14
|
1 |
|
public function __construct($configFilename = '') |
|
15
|
|
|
{ |
|
16
|
1 |
|
if (strlen($configFilename)) { |
|
17
|
|
|
$this->loadConfigFile($configFilename); |
|
18
|
|
|
} |
|
19
|
1 |
|
} |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* Search config key and returns this value |
|
23
|
|
|
* |
|
24
|
|
|
* @param string $key |
|
25
|
|
|
* |
|
26
|
|
|
* @return mixed |
|
27
|
|
|
*/ |
|
28
|
1 |
|
public function getConf($key) |
|
29
|
|
|
{ |
|
30
|
1 |
|
$value = NULL; |
|
31
|
1 |
|
if (count($this->config) > 0) { |
|
32
|
1 |
|
if (array_key_exists($key, $this->config)) { |
|
33
|
1 |
|
$value = $this->config[$key]; |
|
34
|
1 |
|
} |
|
35
|
1 |
|
} |
|
36
|
1 |
|
return $value; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* Set a config parameter |
|
41
|
|
|
* |
|
42
|
|
|
* @param string $key |
|
43
|
|
|
* @param mixed $value |
|
44
|
|
|
* |
|
45
|
|
|
* @return \CloudFramework\Tool\ConfigLoader |
|
46
|
|
|
*/ |
|
47
|
1 |
|
public function setConf($key, $value = NULL) |
|
48
|
|
|
{ |
|
49
|
1 |
|
$this->config[$key] = $value; |
|
50
|
1 |
|
return $this; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* Reload config file |
|
55
|
|
|
* |
|
56
|
|
|
* @param $configFilename |
|
57
|
|
|
* |
|
58
|
|
|
* @throws \Exception |
|
59
|
|
|
*/ |
|
60
|
|
|
public function loadConfigFile($configFilename = '') |
|
61
|
|
|
{ |
|
62
|
|
|
if (0 > strlen($configFilename) && file_exists($configFilename)) { |
|
63
|
|
|
$configs = json_decode(file_get_contents($configFilename), true); |
|
64
|
|
|
$this->extractComposedConfigs($configs); |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
/** |
|
69
|
|
|
* @param array|mixed $configs |
|
70
|
|
|
* @param string $composedKey |
|
71
|
|
|
* @param array $composedConfig |
|
72
|
|
|
* |
|
73
|
|
|
* @return \CloudFramework\Tool\ConfigLoader |
|
74
|
|
|
*/ |
|
75
|
|
|
protected function extractComposedConfigs($configs, $composedKey = '', &$composedConfig = array()) |
|
76
|
|
|
{ |
|
77
|
|
|
if (is_array($configs)) { |
|
78
|
|
|
foreach ($configs as $key => $config) { |
|
79
|
|
|
$_key = strlen($composedKey) ? $composedKey . '.' . $key : $key; |
|
80
|
|
|
if (is_array($config)) { |
|
81
|
|
|
$this->extractComposedConfigs($config, $_key, $composedConfig); |
|
82
|
|
|
} else { |
|
83
|
|
|
$this->setConf($_key, $config); |
|
84
|
|
|
} |
|
85
|
|
|
} |
|
86
|
|
|
} elseif (strlen($composedKey)) { |
|
87
|
|
|
$this->setConf($composedKey, $configs); |
|
88
|
|
|
} |
|
89
|
|
|
|
|
90
|
|
|
return $this; |
|
91
|
|
|
} |
|
92
|
|
|
} |
|
93
|
|
|
|