1
|
|
|
<?php |
2
|
|
|
namespace Monitor\Config; |
3
|
|
|
|
4
|
|
|
use Monitor\Contract\Config\ConfigInterface; |
5
|
|
|
|
6
|
|
|
class ConfigJson implements ConfigInterface |
7
|
|
|
{ |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Config data |
11
|
|
|
* @var array |
12
|
|
|
*/ |
13
|
|
|
private $data; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Load default config values before retrieve from file |
17
|
|
|
* |
18
|
|
|
* @param $filename |
19
|
|
|
* @param array $configValues |
20
|
|
|
*/ |
21
|
|
|
public function __construct($filename = null, array $configValues = []) |
22
|
|
|
{ |
23
|
|
|
$this->data = $configValues; |
24
|
|
|
|
25
|
|
|
if ($filename) { |
26
|
|
|
$this->loadFromFile($filename); |
27
|
|
|
} |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Load config from file |
32
|
|
|
* |
33
|
|
|
* @param string filename |
34
|
|
|
*/ |
35
|
|
|
private function loadFromFile($filename) |
36
|
|
|
{ |
37
|
|
|
$fullPath = $this->getFullPath($filename); |
38
|
|
|
$this->isFileReadable($fullPath); |
39
|
|
|
$configData = file_get_contents($fullPath); |
40
|
|
|
$this->data = $this->decode($configData); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Get config value by key |
45
|
|
|
* |
46
|
|
|
* @param mixed $name |
47
|
|
|
* @param mixed $default |
48
|
|
|
*/ |
49
|
|
|
public function get($name, $default = null) |
50
|
|
|
{ |
51
|
|
|
if (isset($this->data[$name]) |
52
|
|
|
|| $default) { |
53
|
|
|
return isset($this->data[$name]) ? $this->data[$name] : $default; |
54
|
|
|
} |
55
|
|
|
throw new \Exception($name.' not found in config'); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* Get full path of config |
60
|
|
|
* |
61
|
|
|
* @param string $filename |
62
|
|
|
*/ |
63
|
|
|
private function getFullPath($filename) |
64
|
|
|
{ |
65
|
|
|
$fullPath = __DIR__.'/../'.$filename; |
66
|
|
|
return $fullPath; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* Decode json string to array |
71
|
|
|
* |
72
|
|
|
* @param $data |
73
|
|
|
* @return array $decodedData |
74
|
|
|
*/ |
75
|
|
|
private function decode($data) |
76
|
|
|
{ |
77
|
|
|
$decodedData = json_decode($data, true); |
78
|
|
|
if (json_last_error() !== JSON_ERROR_NONE) { |
79
|
|
|
throw new \Exception('Can\'t parse config'); |
80
|
|
|
} |
81
|
|
|
return (array) $decodedData; |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
/** |
85
|
|
|
* Check if config file is readable |
86
|
|
|
* |
87
|
|
|
* @param fullPath |
88
|
|
|
* @throws \Exception |
89
|
|
|
*/ |
90
|
|
|
private function isFileReadable($fullPath) |
91
|
|
|
{ |
92
|
|
|
if (! is_readable($fullPath)) { |
93
|
|
|
throw new \Exception('Config is not readable'); |
94
|
|
|
} |
95
|
|
|
} |
96
|
|
|
} |
97
|
|
|
|