Skip to content

Commit 2b6516e

Browse files
committed
Add available flag FORCE_OBJECT for Json::encode()
1 parent 9d5da31 commit 2b6516e

File tree

2 files changed

+5
-2
lines changed

2 files changed

+5
-2
lines changed

src/Utils/Json.php

+4-2
Original file line numberDiff line numberDiff line change
@@ -23,15 +23,17 @@ final class Json
2323

2424
const PRETTY = 0b0010;
2525

26+
const FORCE_OBJECT = 0b10000;
2627

2728
/**
28-
* Returns the JSON representation of a value. Accepts flag Json::PRETTY.
29+
* Returns the JSON representation of a value. Accepts flag Json::PRETTY and JSON::FORCE_OBJECT.
2930
*/
3031
public static function encode($value, int $flags = 0): string
3132
{
3233
$flags = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
3334
| ($flags & self::PRETTY ? JSON_PRETTY_PRINT : 0)
34-
| (defined('JSON_PRESERVE_ZERO_FRACTION') ? JSON_PRESERVE_ZERO_FRACTION : 0); // since PHP 5.6.6 & PECL JSON-C 1.3.7
35+
| ($flags & self::FORCE_OBJECT ? JSON_FORCE_OBJECT : 0)
36+
| (defined('JSON_PRESERVE_ZERO_FRACTION') ? JSON_PRESERVE_ZERO_FRACTION : 0); // since PHP 5.6.6 & PECL JSON-C 1.3.7
3537

3638
$json = json_encode($value, $flags);
3739
if ($error = json_last_error()) {

tests/Utils/Json.encode().phpt

+1
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ Assert::same('"\u2028\u2029"', Json::encode("\u{2028}\u{2029}"));
3535
// JSON_PRETTY_PRINT
3636
Assert::same("[\n 1,\n 2,\n 3\n]", Json::encode([1, 2, 3], Json::PRETTY));
3737

38+
Assert::same("{}", JSON::encode([], Json::FORCE_OBJECT));
3839

3940
Assert::exception(function () {
4041
Json::encode(NAN);

0 commit comments

Comments
 (0)