|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace TomPHP\ConfigServiceProvider\FileReader; |
|
4
|
|
|
|
|
5
|
|
|
use TomPHP\ConfigServiceProvider\Exception\FileNotFoundException; |
|
6
|
|
|
use TomPHP\ConfigServiceProvider\Exception\InvalidConfigException; |
|
7
|
|
|
use TomPHP\ConfigServiceProvider\FileReader\FileReader; |
|
8
|
|
|
|
|
9
|
|
|
final class JSONFileReader implements FileReader |
|
10
|
|
|
{ |
|
11
|
|
|
private $filename; |
|
12
|
|
|
|
|
13
|
|
|
public function read($filename) |
|
14
|
|
|
{ |
|
15
|
|
|
$this->filename = $filename; |
|
16
|
|
|
|
|
17
|
|
|
$this->assertFileExists(); |
|
18
|
|
|
|
|
19
|
|
|
$config = json_decode(file_get_contents($filename), true); |
|
20
|
|
|
|
|
21
|
|
|
if (json_last_error() !== JSON_ERROR_NONE) { |
|
22
|
|
|
throw InvalidConfigException::fromJSONFileError($filename, $this->getJsonError()); |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
return $config; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
private function assertFileExists() |
|
29
|
|
|
{ |
|
30
|
|
|
if (!file_exists($this->filename)) { |
|
31
|
|
|
throw FileNotFoundException::fromFileName($this->filename); |
|
32
|
|
|
} |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* @return string |
|
37
|
|
|
*/ |
|
38
|
|
|
private function getJsonError() |
|
39
|
|
|
{ |
|
40
|
|
|
if (function_exists('json_last_error_msg')) { |
|
41
|
|
|
return json_last_error_msg(); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
$errors = [ |
|
45
|
|
|
JSON_ERROR_NONE => null, |
|
46
|
|
|
JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', |
|
47
|
|
|
JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch', |
|
48
|
|
|
JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', |
|
49
|
|
|
JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON', |
|
50
|
|
|
JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded', |
|
51
|
|
|
]; |
|
52
|
|
|
|
|
53
|
|
|
return $errors[json_last_error()]; |
|
54
|
|
|
} |
|
55
|
|
|
} |
|
56
|
|
|
|