From cbad7a991f0e56f2c8ac9e099849b044050ec264 Mon Sep 17 00:00:00 2001 From: David Grudl Date: Sun, 9 Jan 2022 13:19:58 +0100 Subject: [PATCH] Json: added additional flags --- src/Utils/Json.php | 9 +++++++-- tests/Utils/Json.encode().phpt | 8 ++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/Utils/Json.php b/src/Utils/Json.php index 02d10a4f2..07290b04a 100644 --- a/src/Utils/Json.php +++ b/src/Utils/Json.php @@ -30,20 +30,25 @@ final class Json /** - * Converts value to JSON format. Use $pretty for easier reading and clarity and $asciiSafe for ASCII output. + * Converts value to JSON format. Use $pretty for easier reading and clarity, $asciiSafe for ASCII output + * and $htmlSafe for HTML escaping, $forceObjects enforces the encoding of non-associateve arrays as objects. * @throws JsonException */ public static function encode( mixed $value, bool|int $pretty = false, bool $asciiSafe = false, + bool $htmlSafe = false, + bool $forceObjects = false, ): string { if (is_int($pretty)) { // back compatibility $flags = ($pretty & self::ESCAPE_UNICODE ? 0 : JSON_UNESCAPED_UNICODE) | ($pretty & ~self::ESCAPE_UNICODE); } else { $flags = ($asciiSafe ? 0 : JSON_UNESCAPED_UNICODE) - | ($pretty ? JSON_PRETTY_PRINT : 0); + | ($pretty ? JSON_PRETTY_PRINT : 0) + | ($forceObjects ? JSON_FORCE_OBJECT : 0) + | ($htmlSafe ? JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_TAG : 0); } $flags |= JSON_UNESCAPED_SLASHES diff --git a/tests/Utils/Json.encode().phpt b/tests/Utils/Json.encode().phpt index cc3cf0193..a70d69c03 100644 --- a/tests/Utils/Json.encode().phpt +++ b/tests/Utils/Json.encode().phpt @@ -46,6 +46,14 @@ Assert::same("[\n 1,\n 2,\n 3\n]", Json::encode([1, 2, 3], Json::PRETTY Assert::same("[\n 1,\n 2,\n 3\n]", Json::encode([1, 2, 3], pretty: true)); +// force objects +Assert::same('{"0":1,"1":2,"2":3}', Json::encode([1, 2, 3], forceObjects: true)); + + +// HTML-safe +Assert::same('"\u003C \u0022 \u0027 \u003E \u0026"', Json::encode("< \" ' > &", htmlSafe: true)); + + Assert::exception( fn() => Json::encode(NAN), Nette\Utils\JsonException::class,