diff --git a/src/Type/Json.php b/src/Type/Json.php index 32b678d..e398f76 100644 --- a/src/Type/Json.php +++ b/src/Type/Json.php @@ -23,14 +23,14 @@ class Json extends ScalarType public string|null $description = 'The `json` scalar type represents json data.'; #[Override] - public function parseLiteral(ASTNode $valueNode, array|null $variables = null): string + public function parseLiteral(ASTNode $valueNode, array|null $variables = null): array|null { // @codeCoverageIgnoreStart if (! $valueNode instanceof StringValueNode) { throw new Error('Query error: Can only parse strings got: ' . $valueNode->kind, $valueNode); } - return $valueNode->value; + return $this->parseValue($valueNode->value); // @codeCoverageIgnoreEnd } @@ -56,8 +56,14 @@ public function parseValue(mixed $value): array|null } #[Override] - public function serialize(mixed $value): false|string + public function serialize(mixed $value): string|false { - return json_encode($value); + $return = json_encode($value); + + if (! $return) { + throw new Error('Could not serialize JSON data'); + } + + return $return; } } diff --git a/test/Feature/Type/JsonTest.php b/test/Feature/Type/JsonTest.php index 57e3179..8e704ab 100644 --- a/test/Feature/Type/JsonTest.php +++ b/test/Feature/Type/JsonTest.php @@ -49,10 +49,18 @@ public function testParseLiteral(): void { $jsonType = new Json(); $node = new StringValueNode([]); - $node->value = 'search string'; + $node->value = '{"field": "value"}'; $result = $jsonType->parseLiteral($node); - $this->assertTrue(true); + $this->assertEquals(['field' => 'value'], $result); + } + + public function testSerializeFails(): void + { + $this->expectException(Error::class); + + $jsonType = new Json(); + $jsonType->serialize(["name" => "\xB1\x31"]); } public function testContains(): void