From f4e27d5cdc73799ebb434a04bf11eefbb274804f Mon Sep 17 00:00:00 2001 From: Greg Bowler Date: Wed, 14 Sep 2022 16:34:54 +0100 Subject: [PATCH] feature: throw correct exceptions closes #5 --- src/JsonDecodeException.php | 10 ++++++++++ src/JsonException.php | 6 ++++++ src/JsonObjectBuilder.php | 10 +++++++++- test/phpunit/JsonObjectBuilderTest.php | 19 ++++++++++++++++++- 4 files changed, 43 insertions(+), 2 deletions(-) create mode 100644 src/JsonDecodeException.php create mode 100644 src/JsonException.php diff --git a/src/JsonDecodeException.php b/src/JsonDecodeException.php new file mode 100644 index 0000000..52cd868 --- /dev/null +++ b/src/JsonDecodeException.php @@ -0,0 +1,10 @@ +fromJsonDecoded($json); } /** - * @param object|array|string|int|float|bool|null $jsonDecoded + * @param object|array|string|int|float|bool|null $jsonDecoded */ public function fromJsonDecoded( object|array|string|int|float|bool|null $jsonDecoded diff --git a/test/phpunit/JsonObjectBuilderTest.php b/test/phpunit/JsonObjectBuilderTest.php index fa22a47..41027a8 100644 --- a/test/phpunit/JsonObjectBuilderTest.php +++ b/test/phpunit/JsonObjectBuilderTest.php @@ -1,6 +1,7 @@ getInt("id")); self::assertEquals("Example", $object->getString("name")); } -} \ No newline at end of file + + public function testFromJson_syntaxError() { + $jsonString = '{ "name": "Greg", "title: "Clumsy programmer!" }'; + $sut = new JsonObjectBuilder(); + self::expectException(JsonDecodeException::class); + self::expectExceptionMessage("Error decoding JSON: Syntax error"); + $sut->fromJsonString($jsonString); + } + + public function testFromJson_illegalCharacters() { + $jsonString = "{ \"name\": \"Greg\", \"favourite_characters\": \"\xB1\x31\" }"; + $sut = new JsonObjectBuilder(); + self::expectException(JsonDecodeException::class); + self::expectExceptionMessage("Error decoding JSON: Malformed UTF-8 characters, possibly incorrectly encoded"); + $sut->fromJsonString($jsonString); + } +}