|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Noodlehaus\Parser; |
|
4
|
|
|
|
|
5
|
|
|
use Noodlehaus\Exception\ParseException; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* JSON parser |
|
9
|
|
|
* |
|
10
|
|
|
* @package Config |
|
11
|
|
|
* @author Jesus A. Domingo <[email protected]> |
|
12
|
|
|
* @author Hassan Khan <[email protected]> |
|
13
|
|
|
* @author Filip Š <[email protected]> |
|
14
|
|
|
* @link https://github.com/noodlehaus/config |
|
15
|
|
|
* @license MIT |
|
16
|
|
|
*/ |
|
17
|
|
|
class Json implements ParserInterface |
|
18
|
|
|
{ |
|
19
|
|
|
/** |
|
20
|
|
|
* {@inheritDoc} |
|
21
|
|
|
* Parses an JSON file as an array |
|
22
|
|
|
* |
|
23
|
|
|
* @throws ParseException If there is an error parsing the JSON file |
|
24
|
|
|
*/ |
|
25
|
6 |
|
public function parseFile($filename) |
|
26
|
|
|
{ |
|
27
|
6 |
|
$data = json_decode(file_get_contents($filename), true); |
|
28
|
|
|
return $this->parse($data, $filename); |
|
|
|
|
|
|
29
|
6 |
|
} |
|
30
|
3 |
|
|
|
31
|
3 |
|
/** |
|
32
|
3 |
|
* {@inheritDoc} |
|
33
|
1 |
|
* Parses an JSON string as an array |
|
34
|
|
|
* |
|
35
|
|
|
* @throws ParseException If there is an error parsing the JSON string |
|
36
|
3 |
|
*/ |
|
37
|
3 |
|
public function parseString($config) |
|
38
|
3 |
|
{ |
|
39
|
1 |
|
$data = json_decode($config, true); |
|
40
|
3 |
|
return $this->parse($data); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
3 |
|
/** |
|
44
|
|
|
* Completes parsing of JSON data |
|
45
|
|
|
* |
|
46
|
|
|
* @param array $data |
|
47
|
|
|
* @param strring $filename |
|
48
|
|
|
* |
|
49
|
3 |
|
* @throws ParseException If there is an error parsing the JSON data |
|
50
|
|
|
*/ |
|
51
|
3 |
|
protected function parse($data = null, $filename = null) |
|
52
|
|
|
{ |
|
53
|
|
|
if (json_last_error() !== JSON_ERROR_NONE) { |
|
54
|
|
|
$error_message = 'Syntax error'; |
|
55
|
|
|
if (function_exists('json_last_error_msg')) { |
|
56
|
|
|
$error_message = json_last_error_msg(); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
$error = [ |
|
60
|
|
|
'message' => $error_message, |
|
61
|
|
|
'type' => json_last_error(), |
|
62
|
|
|
'file' => $filename, |
|
63
|
|
|
]; |
|
64
|
|
|
throw new ParseException($error); |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
return $data; |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
/** |
|
71
|
|
|
* {@inheritDoc} |
|
72
|
|
|
*/ |
|
73
|
|
|
public static function getSupportedExtensions() |
|
74
|
|
|
{ |
|
75
|
|
|
return ['json']; |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|
It seems like the type of the argument is not accepted by the function/method which you are calling.
In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.
We suggest to add an explicit type cast like in the following example: