Skip to content

Commit

Permalink
JsonString a bit better validation and docs.
Browse files Browse the repository at this point in the history
  • Loading branch information
LastDragon-ru committed Sep 15, 2023
1 parent 298f375 commit a54cdd3
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
10 changes: 9 additions & 1 deletion packages/graphql/docs/Scalars/JsonString.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,12 @@

Represents [JSON](https://json.org) string.

Please note that the scalar doesn't encode/decode value to/from JSON, it just contains a valid JSON string. Consider using `JSON` type from [`mll-lab/graphql-php-scalars`](https://github.com/mll-lab/graphql-php-scalars) package if you need a conversion.
Please note that the scalar doesn't encode/decode value to/from JSON, it just contains a valid JSON string. If you want automatically convert value to/from JSON, you can use the `JSON` type from [`mll-lab/graphql-php-scalars`](https://github.com/mll-lab/graphql-php-scalars) package. If you need something more typesafe, consider using [`Serializer`][pkg:serializer].

[include:file]: ../../../../docs/shared/Links.md
[//]: # (start: a170145c7adc0561ead408b0ea3a4b46e2e8f45ebc2744984ceb8c1b49822cd1)
[//]: # (warning: Generated automatically. Do not edit.)

[pkg:serializer]: https://github.com/LastDragon-ru/lara-asp/tree/main/packages/serializer

[//]: # (end: a170145c7adc0561ead408b0ea3a4b46e2e8f45ebc2744984ceb8c1b49822cd1)
12 changes: 8 additions & 4 deletions packages/graphql/src/Scalars/JsonString.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,13 @@ class JsonString extends StringType implements TypeDefinition {
// <editor-fold desc="ScalarType">
// =========================================================================
public function serialize(mixed $value): string {
return $this->validate($value, InvariantViolation::class);
if ($value instanceof JsonStringable) {
$value = (string) $value;
} else {
$value = $this->validate($value, InvariantViolation::class);
}

return $value;
}

public function parseValue(mixed $value): string {
Expand All @@ -49,7 +55,7 @@ public function parseLiteral(Node $valueNode, array $variables = null): string {
);
}

return $this->validate($valueNode->value, Error::class);
return $this->parseValue($valueNode->value);
}

/**
Expand All @@ -60,8 +66,6 @@ public function parseLiteral(Node $valueNode, array $variables = null): string {
protected function validate(mixed $value, string $error): string {
if (is_string($value) && json_validate($value)) {
// ok
} elseif ($value instanceof JsonStringable) {
$value = (string) $value;
} else {
throw new $error(
sprintf(
Expand Down

0 comments on commit a54cdd3

Please sign in to comment.