Skip to content

Commit

Permalink
Add available flag FORCE_OBJECT for Json::encode()
Browse files Browse the repository at this point in the history
  • Loading branch information
integer committed Oct 17, 2017
1 parent 9d5da31 commit acf0abc
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/Utils/Json.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 2 additions & 0 deletions tests/Utils/Json.encode().phpt
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit acf0abc

Please sign in to comment.