Skip to content

Commit 8fe26a1

Browse files
committed
String and ID types should not try to convert non-scalar values to string (#121)
1 parent 5e6acb6 commit 8fe26a1

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

src/Type/Definition/IDType.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
<?php
22
namespace GraphQL\Type\Definition;
33

4+
use GraphQL\Error\UserError;
45
use GraphQL\Language\AST\IntValueNode;
56
use GraphQL\Language\AST\StringValueNode;
7+
use GraphQL\Utils;
68

79
/**
810
* Class IDType
@@ -46,6 +48,12 @@ public function parseValue($value)
4648
if ($value === false) {
4749
return 'false';
4850
}
51+
if ($value === null) {
52+
return 'null';
53+
}
54+
if (!is_scalar($value)) {
55+
throw new UserError("String cannot represent non scalar value: " . Utils::printSafe($value));
56+
}
4957
return (string) $value;
5058
}
5159

src/Type/Definition/StringType.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
<?php
22
namespace GraphQL\Type\Definition;
33

4+
use GraphQL\Error\UserError;
45
use GraphQL\Language\AST\StringValueNode;
6+
use GraphQL\Utils;
57

68
/**
79
* Class StringType
@@ -43,6 +45,12 @@ public function parseValue($value)
4345
if ($value === false) {
4446
return 'false';
4547
}
48+
if ($value === null) {
49+
return 'null';
50+
}
51+
if (!is_scalar($value)) {
52+
throw new UserError("String cannot represent non scalar value: " . Utils::printSafe($value));
53+
}
4654
return (string) $value;
4755
}
4856

tests/Type/ScalarSerializationTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,21 @@ public function testSerializesOutputStrings()
119119
$this->assertSame('-1.1', $stringType->serialize(-1.1));
120120
$this->assertSame('true', $stringType->serialize(true));
121121
$this->assertSame('false', $stringType->serialize(false));
122+
$this->assertSame('null', $stringType->serialize(null));
123+
124+
try {
125+
$stringType->serialize([]);
126+
$this->fail('Expected exception was not thrown');
127+
} catch (UserError $e) {
128+
$this->assertEquals('String cannot represent non scalar value: array', $e->getMessage());
129+
}
130+
131+
try {
132+
$stringType->serialize(new \stdClass());
133+
$this->fail('Expected exception was not thrown');
134+
} catch (UserError $e) {
135+
$this->assertEquals('String cannot represent non scalar value: instance of stdClass', $e->getMessage());
136+
}
122137
}
123138

124139
/**

0 commit comments

Comments
 (0)