Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add JsonUtils::isValidJson #18

Merged
merged 2 commits into from
Nov 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
/.php-cs-fixer.cache
/.phpunit.result.cache
/composer.lock
/tags
/vendor
/.idea
16 changes: 16 additions & 0 deletions src/Json/JsonUtils.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,22 @@ public static function roundTrip($value)
return self::decodeArray(self::encode($value));
}

/**
* Checks if given string is a valid JSON document.
*
* If you want to validate JSON before decoding it for further usage, decode
* it right away and handle JsonUtilsDecodeException instead, as it is way
* more efficient.
*/
public static function isValidJson(string $json): bool
{
if (function_exists('json_validate')) {
return json_validate($json);
}

return json_decode($json, true) !== null || JSON_ERROR_NONE === json_last_error();
}

/** @return mixed */
private static function decodeInternal(string $json, bool $assoc)
{
Expand Down
19 changes: 19 additions & 0 deletions tests/Json/JsonUtilsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,23 @@ public function testDecodeArrayFailure(): void
$json = '"hello';
JsonUtils::decodeArray($json);
}

public function testIsValidJson(): void
{
$json = '{"hello":"world"}';
self::assertTrue(JsonUtils::isValidJson($json));
}

public function testIsValidJsonNull(): void
{
$json = json_encode(null);
self::assertIsString($json);
self::assertTrue(JsonUtils::isValidJson($json));
}

public function testIsValidJsonFailure(): void
{
$json = '';
self::assertFalse(JsonUtils::isValidJson($json));
}
}
Loading