Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
26 / 26 |
|
100.00% |
5 / 5 |
CRAP | |
100.00% |
1 / 1 |
| Json | |
100.00% |
26 / 26 |
|
100.00% |
5 / 5 |
13 | |
100.00% |
1 / 1 |
| parseFile | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
3 | |||
| verifyAndDecode | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
3 | |||
| decode | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
2 | |||
| verify | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
2 | |||
| encode | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
3 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Projom\Util; |
| 6 | |
| 7 | use Projom\Util\File; |
| 8 | |
| 9 | class Json |
| 10 | { |
| 11 | public static function parseFile(string $fullFilePath): null|array |
| 12 | { |
| 13 | if (!$fullFilePath) |
| 14 | return null; |
| 15 | |
| 16 | if (!$json = File::read($fullFilePath)) |
| 17 | return null; |
| 18 | |
| 19 | return static::verifyAndDecode($json); |
| 20 | } |
| 21 | |
| 22 | public static function verifyAndDecode(string $jsonString, bool $asArray = true): null|array |
| 23 | { |
| 24 | if (!$jsonString) |
| 25 | return null; |
| 26 | |
| 27 | $decoded = static::decode($jsonString, $asArray); |
| 28 | |
| 29 | if (json_last_error() !== JSON_ERROR_NONE) |
| 30 | return null; |
| 31 | |
| 32 | return $decoded; |
| 33 | } |
| 34 | |
| 35 | public static function decode(string $jsonString, bool $asArray = true): null|array |
| 36 | { |
| 37 | if (!$jsonString) |
| 38 | return null; |
| 39 | |
| 40 | $decoded = json_decode($jsonString, $asArray); |
| 41 | return $decoded; |
| 42 | } |
| 43 | |
| 44 | public static function verify(string $jsonString): bool |
| 45 | { |
| 46 | if (!$jsonString) |
| 47 | return false; |
| 48 | |
| 49 | static::decode($jsonString); |
| 50 | return json_last_error() === JSON_ERROR_NONE; |
| 51 | } |
| 52 | |
| 53 | public static function encode(array $toEncode, bool $prettyPrint = false): null|string |
| 54 | { |
| 55 | $flags = 0; |
| 56 | if ($prettyPrint) |
| 57 | $flags = JSON_PRETTY_PRINT; |
| 58 | |
| 59 | $encoded = json_encode($toEncode, $flags); |
| 60 | if ($encoded === false) |
| 61 | return null; |
| 62 | |
| 63 | return $encoded; |
| 64 | } |
| 65 | } |