Skip to content

Commit

Permalink
Json: added additional flags
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Jan 19, 2023
1 parent 3fdce10 commit cbad7a9
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/Utils/Json.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,20 +30,25 @@ final class Json


/**
* Converts value to JSON format. Use $pretty for easier reading and clarity and $asciiSafe for ASCII output.
* Converts value to JSON format. Use $pretty for easier reading and clarity, $asciiSafe for ASCII output
* and $htmlSafe for HTML escaping, $forceObjects enforces the encoding of non-associateve arrays as objects.
* @throws JsonException
*/
public static function encode(
mixed $value,
bool|int $pretty = false,
bool $asciiSafe = false,
bool $htmlSafe = false,
bool $forceObjects = false,
): string
{
if (is_int($pretty)) { // back compatibility
$flags = ($pretty & self::ESCAPE_UNICODE ? 0 : JSON_UNESCAPED_UNICODE) | ($pretty & ~self::ESCAPE_UNICODE);
} else {
$flags = ($asciiSafe ? 0 : JSON_UNESCAPED_UNICODE)
| ($pretty ? JSON_PRETTY_PRINT : 0);
| ($pretty ? JSON_PRETTY_PRINT : 0)
| ($forceObjects ? JSON_FORCE_OBJECT : 0)
| ($htmlSafe ? JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_TAG : 0);
}

$flags |= JSON_UNESCAPED_SLASHES
Expand Down
8 changes: 8 additions & 0 deletions tests/Utils/Json.encode().phpt
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,14 @@ Assert::same("[\n 1,\n 2,\n 3\n]", Json::encode([1, 2, 3], Json::PRETTY
Assert::same("[\n 1,\n 2,\n 3\n]", Json::encode([1, 2, 3], pretty: true));


// force objects
Assert::same('{"0":1,"1":2,"2":3}', Json::encode([1, 2, 3], forceObjects: true));


// HTML-safe
Assert::same('"\u003C \u0022 \u0027 \u003E \u0026"', Json::encode("< \" ' > &", htmlSafe: true));


Assert::exception(
fn() => Json::encode(NAN),
Nette\Utils\JsonException::class,
Expand Down

0 comments on commit cbad7a9

Please sign in to comment.