|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace TomPHP\ConfigServiceProvider; |
|
4
|
|
|
|
|
5
|
|
|
use ArrayAccess; |
|
6
|
|
|
use TomPHP\ConfigServiceProvider\Exception\EntryDoesNotExistException; |
|
7
|
|
|
use TomPHP\ConfigServiceProvider\Exception\ReadOnlyException; |
|
8
|
|
|
|
|
9
|
|
|
final class Config implements ArrayAccess |
|
10
|
|
|
{ |
|
11
|
|
|
/** |
|
12
|
|
|
* @var array |
|
13
|
|
|
*/ |
|
14
|
|
|
private $config; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* @var string |
|
18
|
|
|
*/ |
|
19
|
|
|
private $separator; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* @param string $separator |
|
23
|
|
|
*/ |
|
24
|
|
|
public function __construct(array $config, $separator = '.') |
|
25
|
|
|
{ |
|
26
|
|
|
$this->config = $config; |
|
27
|
|
|
$this->separator = $separator; |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
public function offsetExists($offset) |
|
31
|
|
|
{ |
|
32
|
|
|
try { |
|
33
|
|
|
$this->traverseConfig($this->getPath($offset)); |
|
34
|
|
|
} catch (EntryDoesNotExistException $e) { |
|
35
|
|
|
return false; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
return true; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
public function offsetGet($offset) |
|
42
|
|
|
{ |
|
43
|
|
|
return $this->traverseConfig($this->getPath($offset)); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
public function offsetSet($offset, $value) |
|
47
|
|
|
{ |
|
48
|
|
|
throw new ReadOnlyException('Config is read only.'); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
public function offsetUnset($offset) |
|
52
|
|
|
{ |
|
53
|
|
|
throw new ReadOnlyException('Config is read only.'); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
/** |
|
57
|
|
|
* @return array |
|
58
|
|
|
*/ |
|
59
|
|
|
public function asArray() |
|
60
|
|
|
{ |
|
61
|
|
|
return $this->config; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
/** |
|
65
|
|
|
* @return string |
|
66
|
|
|
*/ |
|
67
|
|
|
public function getSeparator() |
|
68
|
|
|
{ |
|
69
|
|
|
return $this->separator; |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
private function getPath($offset) |
|
73
|
|
|
{ |
|
74
|
|
|
return explode($this->separator, $offset); |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
|
|
private function traverseConfig(array $path) |
|
|
|
|
|
|
78
|
|
|
{ |
|
79
|
|
|
$pointer = &$this->config; |
|
80
|
|
|
|
|
81
|
|
|
foreach ($path as $node) { |
|
82
|
|
|
if (!is_array($pointer) || !array_key_exists($node, $pointer)) { |
|
83
|
|
|
throw new EntryDoesNotExistException("No entry found for " . implode($this->separator, $path)); |
|
|
|
|
|
|
84
|
|
|
} |
|
85
|
|
|
|
|
86
|
|
|
$pointer = &$pointer[$node]; |
|
87
|
|
|
} |
|
88
|
|
|
|
|
89
|
|
|
return $pointer; |
|
90
|
|
|
} |
|
91
|
|
|
} |
|
92
|
|
|
|
Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a
@returnannotation as described here.