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 16, 2017
1 parent 9d5da31 commit 2b6516e
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/Utils/Json.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +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)
| (defined('JSON_PRESERVE_ZERO_FRACTION') ? JSON_PRESERVE_ZERO_FRACTION : 0); // since PHP 5.6.6 & PECL JSON-C 1.3.7
| ($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);
if ($error = json_last_error()) {
Expand Down
1 change: 1 addition & 0 deletions tests/Utils/Json.encode().phpt
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ 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([], Json::FORCE_OBJECT));

Assert::exception(function () {
Json::encode(NAN);
Expand Down

0 comments on commit 2b6516e

Please sign in to comment.