Skip to content
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
10 changes: 10 additions & 0 deletions src/JsonDecodeException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php
namespace Gt\Json;

use Throwable;

class JsonDecodeException extends JsonException {
public function __construct(string $message = "", int $code = 0, ?Throwable $previous = null) {
parent::__construct("Error decoding JSON: $message", $code, $previous);
}
}
6 changes: 6 additions & 0 deletions src/JsonException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?php
namespace Gt\Json;

use RuntimeException;

class JsonException extends RuntimeException {}
10 changes: 9 additions & 1 deletion src/JsonObjectBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,19 @@
class JsonObjectBuilder extends DataObjectBuilder {
public function fromJsonString(string $jsonString):JsonObject {
$json = json_decode($jsonString);
if(is_null($json)) {
// It's completely reasonable to have a null value here, so we need to check the
// error code before throwing an exception.
if(json_last_error() !== JSON_ERROR_NONE) {
throw new JsonDecodeException(json_last_error_msg());
}
}

return $this->fromJsonDecoded($json);
}

/**
* @param object|array<mixed>|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
Expand Down
19 changes: 18 additions & 1 deletion test/phpunit/JsonObjectBuilderTest.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php
namespace Gt\Json\Test;

use Gt\Json\JsonDecodeException;
use Gt\Json\JsonKvpObject;
use Gt\Json\JsonObjectBuilder;
use Gt\Json\JsonPrimitive\JsonArrayPrimitive;
Expand Down Expand Up @@ -177,4 +178,20 @@ public function testFromJsonStringArrayContainingSimpleKVP() {
self::assertEquals(123, $object->getInt("id"));
self::assertEquals("Example", $object->getString("name"));
}
}

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);
}
}