1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Basis; |
4
|
|
|
|
5
|
|
|
use ArrayAccess; |
6
|
|
|
|
7
|
|
|
class Config implements ArrayAccess |
8
|
|
|
{ |
9
|
|
|
private $converter; |
10
|
|
|
|
11
|
12 |
|
public function __construct(Framework $framework, Filesystem $fs, Converter $converter) |
12
|
|
|
{ |
13
|
12 |
|
$this->converter = $converter; |
14
|
|
|
|
15
|
12 |
|
$filename = $fs->getPath("config.php"); |
16
|
12 |
|
if (!file_exists($filename)) { |
17
|
|
|
$filename = $framework->getPath('resources/default/config.php'); |
18
|
|
|
} |
19
|
12 |
|
$data = include $filename; |
20
|
12 |
|
foreach ($data as $k => $v) { |
21
|
12 |
|
if (is_callable($v)) { |
22
|
12 |
|
$v = $v(); |
23
|
|
|
} |
24
|
12 |
|
$this->$k = $v; |
25
|
12 |
|
if (is_array($v) || is_object($v)) { |
26
|
12 |
|
$this->$k = $converter->toObject($v); |
27
|
|
|
} |
28
|
|
|
} |
29
|
12 |
|
} |
30
|
|
|
|
31
|
1 |
|
public function offsetExists($offset) |
32
|
|
|
{ |
33
|
1 |
|
return $this->getNode($offset) != null; |
34
|
|
|
} |
35
|
|
|
|
36
|
12 |
|
public function offsetGet($offset) |
37
|
|
|
{ |
38
|
12 |
|
$value = $this->getNode($offset); |
39
|
12 |
|
if (!is_object($value)) { |
40
|
12 |
|
return $value; |
41
|
|
|
} |
42
|
|
|
|
43
|
6 |
|
return $this->converter->toArray($value); |
44
|
|
|
} |
45
|
|
|
|
46
|
1 |
|
public function offsetSet($offset, $value) |
47
|
|
|
{ |
48
|
1 |
|
$path = explode('.', $offset); |
49
|
1 |
|
$key = array_pop($path); |
50
|
1 |
|
$parent = $this->getNode(implode('.', $path), true); |
51
|
1 |
|
if (is_array($value) || is_object($value)) { |
52
|
|
|
$value = $this->converter->toObject($value); |
53
|
|
|
} |
54
|
|
|
|
55
|
1 |
|
return $parent->$key = $value; |
56
|
|
|
} |
57
|
|
|
|
58
|
1 |
|
public function offsetUnset($offset) |
59
|
|
|
{ |
60
|
1 |
|
$path = explode('.', $offset); |
61
|
1 |
|
$key = array_pop($path); |
62
|
1 |
|
$parent = $this->getNode(implode('.', $path)); |
63
|
1 |
|
unset($parent->$key); |
64
|
1 |
|
} |
65
|
|
|
|
66
|
|
|
public function require(string $offset) |
67
|
|
|
{ |
68
|
|
|
if (!isset($this[$offset])) { |
69
|
|
|
throw new Exception("No offset $offset"); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|
73
|
12 |
|
private function getNode(string $offset, bool $createIfNone = false) |
74
|
|
|
{ |
75
|
12 |
|
if (!$offset) { |
76
|
1 |
|
return $this; |
77
|
|
|
} |
78
|
12 |
|
$current = $this; |
79
|
12 |
|
foreach (explode('.', $offset) as $key) { |
80
|
12 |
|
if (is_object($current)) { |
81
|
12 |
|
if (!property_exists($current, $key)) { |
82
|
1 |
|
if ($createIfNone) { |
83
|
1 |
|
$current->$key = (object) []; |
84
|
|
|
} else { |
85
|
1 |
|
return null; |
86
|
|
|
} |
87
|
|
|
} |
88
|
12 |
|
$current = $current->$key; |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|
92
|
12 |
|
return $current; |
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
|