String and ID types should not try to convert non-scalar values to string (#121)

This commit is contained in:
Vladimir Razuvaev 2017-07-18 00:25:45 +07:00
parent 5e6acb60a6
commit 8fe26a1a21
3 changed files with 31 additions and 0 deletions

View File

@ -1,8 +1,10 @@
<?php
namespace GraphQL\Type\Definition;
use GraphQL\Error\UserError;
use GraphQL\Language\AST\IntValueNode;
use GraphQL\Language\AST\StringValueNode;
use GraphQL\Utils;
/**
* Class IDType
@ -46,6 +48,12 @@ When expected as an input type, any string (such as `"4"`) or integer
if ($value === false) {
return 'false';
}
if ($value === null) {
return 'null';
}
if (!is_scalar($value)) {
throw new UserError("String cannot represent non scalar value: " . Utils::printSafe($value));
}
return (string) $value;
}

View File

@ -1,7 +1,9 @@
<?php
namespace GraphQL\Type\Definition;
use GraphQL\Error\UserError;
use GraphQL\Language\AST\StringValueNode;
use GraphQL\Utils;
/**
* Class StringType
@ -43,6 +45,12 @@ represent free-form human-readable text.';
if ($value === false) {
return 'false';
}
if ($value === null) {
return 'null';
}
if (!is_scalar($value)) {
throw new UserError("String cannot represent non scalar value: " . Utils::printSafe($value));
}
return (string) $value;
}

View File

@ -119,6 +119,21 @@ class ScalarSerializationTest extends \PHPUnit_Framework_TestCase
$this->assertSame('-1.1', $stringType->serialize(-1.1));
$this->assertSame('true', $stringType->serialize(true));
$this->assertSame('false', $stringType->serialize(false));
$this->assertSame('null', $stringType->serialize(null));
try {
$stringType->serialize([]);
$this->fail('Expected exception was not thrown');
} catch (UserError $e) {
$this->assertEquals('String cannot represent non scalar value: array', $e->getMessage());
}
try {
$stringType->serialize(new \stdClass());
$this->fail('Expected exception was not thrown');
} catch (UserError $e) {
$this->assertEquals('String cannot represent non scalar value: instance of stdClass', $e->getMessage());
}
}
/**