1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace ntentan\config; |
4
|
|
|
|
5
|
|
|
class Config |
6
|
|
|
{ |
7
|
|
|
|
8
|
|
|
private $config; |
9
|
|
|
private $context = 'default'; |
10
|
|
|
|
11
|
|
|
public function __construct($path = null, $namespace = null) { |
12
|
|
|
if (is_dir($path)) { |
13
|
|
|
$dir = new Directory($path); |
14
|
|
|
$this->config = ['default' => $this->expand($dir->parse(), $namespace)]; |
15
|
|
|
foreach ($dir->getContexts() as $context) { |
16
|
|
|
$this->config[$context] = array_merge( |
17
|
|
|
$this->config['default'], $this->expand($dir->parse($context), $namespace) |
18
|
|
|
); |
19
|
|
|
} |
20
|
|
|
} else if (is_file($path)) { |
21
|
|
|
$this->config[$this->context] = $this->expand(File::read($path), $namespace); |
22
|
|
|
} |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
public static function readDirectory($path, $namespace = null) { |
26
|
|
|
return new Config($path, $namespace); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function isKeySet($key) { |
30
|
|
|
return isset($this->config[$this->context][$key]); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function get($key) { |
34
|
|
|
return $this->config[$this->context][$key]; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
public function setContext($context) { |
38
|
|
|
$this->context = $context; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
public function set($key, $value) { |
42
|
|
|
$keys = explode('.', $key); |
43
|
|
|
$this->config[$this->context] = $this->setValue($keys, $value, $this->config[$this->context]); |
44
|
|
|
$this->config[$this->context][$key] = $value; |
45
|
|
|
if (is_array($value)) { |
46
|
|
|
$this->config[$this->context] += $this->expand($value, null, $key); |
47
|
|
|
} |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
private function setValue($keys, $value, $config) { |
51
|
|
|
if (!empty($keys)) { |
52
|
|
|
$key = array_shift($keys); |
53
|
|
|
$config[$key] = $this->setValue($keys, $value, isset($config[$key]) ? $config[$key] : []); |
54
|
|
|
return $config; |
55
|
|
|
} else { |
56
|
|
|
return $value; |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
private function expand($array, $namespace, $prefix = null) { |
61
|
|
|
$config = []; |
62
|
|
|
if (!is_array($array)) |
63
|
|
|
return $config; |
64
|
|
|
$dottedNamespace = $namespace ? "$namespace:" : ""; |
65
|
|
|
$dottedPrefix = $prefix ? "$prefix." : ""; |
66
|
|
|
foreach ($array as $key => $value) { |
67
|
|
|
$newPrefix = $dottedNamespace . $dottedPrefix . $key; |
68
|
|
|
$config[$newPrefix] = $value; |
69
|
|
|
$config += $this->expand($value, null, $newPrefix); |
70
|
|
|
} |
71
|
|
|
if ($prefix) |
72
|
|
|
$config[$prefix] = $array; |
73
|
|
|
return $config; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
} |
77
|
|
|
|