Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
31.25% |
5 / 16 |
|
0.00% |
0 / 1 |
CRAP | |
0.00% |
0 / 1 |
JSON | |
31.25% |
5 / 16 |
|
0.00% |
0 / 1 |
88.11 | |
0.00% |
0 / 1 |
decode | |
31.25% |
5 / 16 |
|
0.00% |
0 / 1 |
88.11 |
1 | <?php |
2 | /** @noinspection PhpUnhandledExceptionInspection */ |
3 | declare(strict_types=1); |
4 | // TODO unit test |
5 | // TODO throw other Exceptions, so we don't get a 500 on malformed json |
6 | |
7 | class JSON { |
8 | static function decode(?string $json, bool $assoc = false) { |
9 | if (!$json) { |
10 | return $assoc ? [] : new stdClass(); |
11 | } |
12 | |
13 | $decoded = json_decode($json, $assoc, 512, JSON_UNESCAPED_UNICODE); |
14 | |
15 | switch (json_last_error()) { |
16 | case JSON_ERROR_NONE: |
17 | return $decoded; |
18 | case JSON_ERROR_DEPTH: |
19 | throw new Exception('JSON Error: Maximum stack depth exceeded'); |
20 | case JSON_ERROR_STATE_MISMATCH: |
21 | throw new Exception('JSON Error: Underflow or the modes mismatch'); |
22 | case JSON_ERROR_CTRL_CHAR: |
23 | throw new Exception('JSON Error: Unexpected control character found'); |
24 | case JSON_ERROR_SYNTAX: |
25 | throw new Exception('JSON Error: Syntax error, malformed JSON'); |
26 | case JSON_ERROR_UTF8: |
27 | throw new Exception('JSON Error: Malformed UTF-8 characters, possibly incorrectly encoded'); |
28 | case JSON_ERROR_RECURSION: |
29 | throw new Exception('JSON Error: One or more recursive references in the value to be encoded'); |
30 | case JSON_ERROR_INF_OR_NAN: |
31 | throw new Exception('JSON Error: One or more NAN or INF values in the value to be encoded'); |
32 | case JSON_ERROR_UNSUPPORTED_TYPE: |
33 | throw new Exception('JSON Error: A value of a type that cannot be encoded was given'); |
34 | case JSON_ERROR_INVALID_PROPERTY_NAME: |
35 | throw new Exception('JSON Error: A property name that cannot be encoded was given'); |
36 | case JSON_ERROR_UTF16: |
37 | throw new Exception('JSON Error: Malformed UTF-16 characters, possibly incorrectly encoded'); |
38 | default: |
39 | throw new Exception('JSON Error: Unknown error'); |
40 | } |
41 | } |
42 | } |