HexMakina /
LocalFS
| 1 | <?php |
||
| 2 | |||
| 3 | namespace HexMakina\LocalFS\Text; |
||
| 4 | |||
| 5 | class JSON extends TextFile |
||
| 6 | { |
||
| 7 | /** |
||
| 8 | * @param int<1, max> $depth |
||
| 9 | */ |
||
| 10 | public static function to_php(string $string, ?bool $assoc = false, int $depth = 512, int $options = 0) |
||
| 11 | { |
||
| 12 | // https://www.php.net/manual/en/function.json-decode.php |
||
| 13 | $ret = json_decode($string, $assoc, $depth, $options); |
||
| 14 | |||
| 15 | $error = self::hasErrors(); |
||
| 16 | if ($error !== false) { |
||
|
0 ignored issues
–
show
introduced
by
Loading history...
|
|||
| 17 | throw new \Exception("ParsingException: $error"); |
||
| 18 | } |
||
| 19 | |||
| 20 | return $ret; |
||
| 21 | } |
||
| 22 | |||
| 23 | /** |
||
| 24 | * @param int<1, max> $depth |
||
| 25 | */ |
||
| 26 | public static function from_php($var, $options = 0, $depth = 512): string |
||
| 27 | { |
||
| 28 | // https://www.php.net/manual/en/function.json-encode.php |
||
| 29 | $ret = json_encode($var, $options, $depth); |
||
| 30 | |||
| 31 | $error = self::hasErrors(); |
||
| 32 | if ($error !== false) { |
||
|
0 ignored issues
–
show
|
|||
| 33 | throw new \Exception("ParsingException: $error"); |
||
| 34 | } |
||
| 35 | |||
| 36 | return $ret; |
||
| 37 | } |
||
| 38 | |||
| 39 | private static function hasErrors() : bool |
||
| 40 | { |
||
| 41 | if (json_last_error() === JSON_ERROR_NONE) { |
||
| 42 | return false; |
||
| 43 | } |
||
| 44 | throw new \Exception('ParsingException: '.json_last_error_msg());; |
||
| 45 | } |
||
| 46 | } |
||
| 47 |