1
|
|
|
<?php |
2
|
|
|
namespace Monitor\Config; |
3
|
|
|
|
4
|
|
|
class ConfigJson implements ConfigInterface |
5
|
|
|
{ |
6
|
|
|
|
7
|
|
|
private $data; |
8
|
|
|
|
9
|
|
|
public function __construct($filename = null, array $configValues = []) |
10
|
|
|
{ |
11
|
|
|
$this->data = $configValues; |
12
|
|
|
|
13
|
|
|
if ($filename) { |
14
|
|
|
$this->loadFromFile($filename); |
15
|
|
|
} |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
private function loadFromFile($filename) |
19
|
|
|
{ |
20
|
|
|
$fullPath = $this->getFullPath($filename); |
21
|
|
|
$this->isFileReadable($fullPath); |
22
|
|
|
$configData = file_get_contents($fullPath); |
23
|
|
|
$this->data = $this->decode($configData); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
public function get($name, $default = null) |
27
|
|
|
{ |
28
|
|
|
if (isset($this->data[$name]) |
29
|
|
|
|| $default) { |
30
|
|
|
return isset($this->data[$name]) ? $this->data[$name] : $default; |
31
|
|
|
} |
32
|
|
|
throw new \Exception($name.' not found in Config'); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
private function getFullPath($filename) |
36
|
|
|
{ |
37
|
|
|
$fullPath = __DIR__.'/../'.$filename; |
38
|
|
|
return $fullPath; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Decode json string to array |
43
|
|
|
* |
44
|
|
|
* @param $data |
45
|
|
|
* @return array $decodedData |
46
|
|
|
*/ |
47
|
|
|
private function decode($data) |
48
|
|
|
{ |
49
|
|
|
$decodedData = json_decode($data, true); |
50
|
|
|
if (json_last_error() !== JSON_ERROR_NONE) { |
51
|
|
|
throw new \Exception('Can\'t parse config'); |
52
|
|
|
} |
53
|
|
|
return (array) $decodedData; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* |
58
|
|
|
* @param fullPath |
59
|
|
|
*/ |
60
|
|
|
private function isFileReadable($fullPath) |
61
|
|
|
{ |
62
|
|
|
if (! is_readable($fullPath)) { |
63
|
|
|
throw new \Exception('config is not readable'); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|