From acf0abc6fd281abaa29894a97610ef0a2d3ef30f Mon Sep 17 00:00:00 2001 From: Pavel Kacha Date: Mon, 16 Oct 2017 21:42:01 +0200 Subject: [PATCH] Add available flag FORCE_OBJECT for Json::encode() --- src/Utils/Json.php | 5 ++++- tests/Utils/Json.encode().phpt | 2 ++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/Utils/Json.php b/src/Utils/Json.php index 2b4f12570..c06e1f230 100644 --- a/src/Utils/Json.php +++ b/src/Utils/Json.php @@ -23,14 +23,17 @@ final class Json const PRETTY = 0b0010; + const FORCE_OBJECT = 0b10000; + /** - * Returns the JSON representation of a value. Accepts flag Json::PRETTY. + * Returns the JSON representation of a value. Accepts flag Json::PRETTY and JSON::FORCE_OBJECT. */ public static function encode($value, int $flags = 0): string { $flags = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | ($flags & self::PRETTY ? JSON_PRETTY_PRINT : 0) + | ($flags & self::FORCE_OBJECT ? JSON_FORCE_OBJECT : 0) | (defined('JSON_PRESERVE_ZERO_FRACTION') ? JSON_PRESERVE_ZERO_FRACTION : 0); // since PHP 5.6.6 & PECL JSON-C 1.3.7 $json = json_encode($value, $flags); diff --git a/tests/Utils/Json.encode().phpt b/tests/Utils/Json.encode().phpt index ba84bbfd1..9888baf1b 100644 --- a/tests/Utils/Json.encode().phpt +++ b/tests/Utils/Json.encode().phpt @@ -35,6 +35,8 @@ Assert::same('"\u2028\u2029"', Json::encode("\u{2028}\u{2029}")); // JSON_PRETTY_PRINT Assert::same("[\n 1,\n 2,\n 3\n]", Json::encode([1, 2, 3], Json::PRETTY)); +Assert::same('[]', JSON::encode([])); +Assert::same('{}', JSON::encode([], Json::FORCE_OBJECT)); Assert::exception(function () { Json::encode(NAN);