1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Config.php |
4
|
|
|
* |
5
|
|
|
* @package Faulancer\Service |
6
|
|
|
* @author Florian Knapp <[email protected]> |
7
|
|
|
*/ |
8
|
|
|
namespace Faulancer\Service; |
9
|
|
|
|
10
|
|
|
use Faulancer\Exception\ConfigInvalidException; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Represents a configuration array |
14
|
|
|
*/ |
15
|
|
|
class Config |
16
|
|
|
{ |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Holds the configuration data |
20
|
|
|
* @var array |
21
|
|
|
*/ |
22
|
|
|
protected $_config = []; |
23
|
|
|
|
24
|
|
|
protected $temp_conf = []; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Set configuration value by key |
28
|
|
|
* |
29
|
|
|
* @param string $key |
30
|
|
|
* @param mixed $value |
31
|
|
|
* @param boolean $force |
32
|
|
|
* @return boolean |
33
|
|
|
* @throws ConfigInvalidException |
34
|
|
|
*/ |
35
|
|
|
public function set($key, $value = null, $force = false) |
36
|
|
|
{ |
37
|
|
|
if (is_array($key) && $value === null) { |
38
|
|
|
foreach ($key as $k => $v) { |
39
|
|
|
$this->set($k, $v); |
40
|
|
|
} |
41
|
|
|
return true; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
if ($force || empty($this->_config[$key])) { |
45
|
|
|
$this->_config[$key] = $value; |
46
|
|
|
return true; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
throw new ConfigInvalidException(); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* Get configuration value by key |
54
|
|
|
* @param string $key |
55
|
|
|
* @return mixed |
56
|
|
|
* @throws ConfigInvalidException |
57
|
|
|
*/ |
58
|
|
|
public function get($key) |
59
|
|
|
{ |
60
|
|
|
if (strpos($key, ':') !== false) { |
61
|
|
|
return $this->recursive($key); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
if (empty($this->_config[$key])) { |
65
|
|
|
throw new ConfigInvalidException('No value for key "' . $key . '" found.'); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
return $this->_config[$key]; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* @param $key |
73
|
|
|
* @return array|mixed |
74
|
|
|
* @throws ConfigInvalidException |
75
|
|
|
*/ |
76
|
|
|
private function recursive($key) |
77
|
|
|
{ |
78
|
|
|
$parts = explode(':', $key); |
79
|
|
|
$result = $this->_config; |
80
|
|
|
|
81
|
|
|
foreach ($parts as $part) { |
82
|
|
|
|
83
|
|
|
if (empty($result[$part])) { |
84
|
|
|
return ''; |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
$result = $result[$part]; |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
return $result; |
91
|
|
|
} |
92
|
|
|
|
93
|
|
|
} |