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