diff --git a/src/Utils/Json.php b/src/Utils/Json.php index 719c87c7..7dbb06e2 100644 --- a/src/Utils/Json.php +++ b/src/Utils/Json.php @@ -27,6 +27,8 @@ final class Json /** @deprecated use Json::encode(..., asciiSafe: true) */ public const ESCAPE_UNICODE = 1 << 19; + public const Ignore = 1; + public const Substitute = 2; /** @@ -40,6 +42,7 @@ public static function encode( bool $asciiSafe = false, bool $htmlSafe = false, bool $forceObjects = false, + int $invalidUtf8 = 0, ): string { $flags = is_int($pretty) // back compatibility @@ -47,7 +50,9 @@ public static function encode( : ($asciiSafe ? 0 : JSON_UNESCAPED_UNICODE) | ($pretty ? JSON_PRETTY_PRINT : 0) | ($forceObjects ? JSON_FORCE_OBJECT : 0) - | ($htmlSafe ? JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_TAG : 0); + | ($htmlSafe ? JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_TAG : 0) + | ($invalidUtf8 === self::Ignore ? JSON_INVALID_UTF8_IGNORE : 0) + | ($invalidUtf8 === self::Substitute ? JSON_INVALID_UTF8_SUBSTITUTE : 0); $flags |= JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION; @@ -64,11 +69,17 @@ public static function encode( * Decodes a JSON string to a PHP value. Use $forceArrays to decode objects as arrays. * @throws JsonException */ - public static function decode(string $json, bool|int $forceArrays = false): mixed + public static function decode( + string $json, + bool|int $forceArrays = false, + int $invalidUtf8 = 0, + ): mixed { $flags = is_int($forceArrays) // back compatibility ? $forceArrays - : ($forceArrays ? JSON_OBJECT_AS_ARRAY : 0); + : (($forceArrays ? JSON_OBJECT_AS_ARRAY : 0) + | ($invalidUtf8 === self::Ignore ? JSON_INVALID_UTF8_IGNORE : 0) + | ($invalidUtf8 === self::Substitute ? JSON_INVALID_UTF8_SUBSTITUTE : 0)); $flags |= JSON_BIGINT_AS_STRING; $value = json_decode($json, flags: $flags); @@ -78,4 +89,14 @@ public static function decode(string $json, bool|int $forceArrays = false): mixe return $value; } + + + /** + * Converts given JSON file to PHP value. + * @throws JsonException + */ + public static function decodeFile(string $file, bool $forceArray = false): mixed + { + return self::decode(FileSystem::read($file), $forceArray); + } }