Skip to content

Commit acf0abc

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

File tree

2 files changed

+6
-1
lines changed

2 files changed

+6
-1
lines changed

src/Utils/Json.php

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

2424
const PRETTY = 0b0010;
2525

26+
const FORCE_OBJECT = 0b10000;
27+
2628

2729
/**
28-
* Returns the JSON representation of a value. Accepts flag Json::PRETTY.
30+
* Returns the JSON representation of a value. Accepts flag Json::PRETTY and JSON::FORCE_OBJECT.
2931
*/
3032
public static function encode($value, int $flags = 0): string
3133
{
3234
$flags = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
3335
| ($flags & self::PRETTY ? JSON_PRETTY_PRINT : 0)
36+
| ($flags & self::FORCE_OBJECT ? JSON_FORCE_OBJECT : 0)
3437
| (defined('JSON_PRESERVE_ZERO_FRACTION') ? JSON_PRESERVE_ZERO_FRACTION : 0); // since PHP 5.6.6 & PECL JSON-C 1.3.7
3538

3639
$json = json_encode($value, $flags);

tests/Utils/Json.encode().phpt

+2
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ 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([]));
39+
Assert::same('{}', JSON::encode([], Json::FORCE_OBJECT));
3840

3941
Assert::exception(function () {
4042
Json::encode(NAN);

0 commit comments

Comments
 (0)