Skip to content

Commit bb75586

Browse files
authored
Merge pull request #210 from enumag/patch-1
Allow objects with __toString in IDType
2 parents 3536280 + 9e2c1da commit bb75586

File tree

3 files changed

+45
-1
lines changed

3 files changed

+45
-1
lines changed

src/Type/Definition/IDType.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ public function serialize($value)
4343
if ($value === null) {
4444
return 'null';
4545
}
46-
if (!is_scalar($value)) {
46+
if (!is_scalar($value) && (!is_object($value) || !method_exists($value, '__toString'))) {
4747
throw new InvariantViolation("ID type cannot represent non scalar value: " . Utils::printSafe($value));
4848
}
4949
return (string) $value;

tests/Type/ObjectIdStub.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<?php
2+
namespace GraphQL\Tests\Type;
3+
4+
class ObjectIdStub
5+
{
6+
/**
7+
* @var int
8+
*/
9+
private $id;
10+
11+
/**
12+
* @param int $id
13+
*/
14+
public function __construct($id)
15+
{
16+
$this->id = $id;
17+
}
18+
19+
public function __toString()
20+
{
21+
return (string) $this->id;
22+
}
23+
}

tests/Type/ScalarSerializationTest.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,4 +178,25 @@ public function testSerializesOutputBoolean()
178178

179179
// TODO: how should it behave on '0'?
180180
}
181+
182+
public function testSerializesOutputID()
183+
{
184+
$idType = Type::id();
185+
186+
$this->assertSame('string', $idType->serialize('string'));
187+
$this->assertSame('', $idType->serialize(''));
188+
$this->assertSame('1', $idType->serialize('1'));
189+
$this->assertSame('1', $idType->serialize(1));
190+
$this->assertSame('0', $idType->serialize(0));
191+
$this->assertSame('true', $idType->serialize(true));
192+
$this->assertSame('false', $idType->serialize(false));
193+
$this->assertSame('2', $idType->serialize(new ObjectIdStub(2)));
194+
195+
try {
196+
$idType->serialize(new \stdClass());
197+
$this->fail('Expected exception was not thrown');
198+
} catch (InvariantViolation $e) {
199+
$this->assertEquals('ID type cannot represent non scalar value: instance of stdClass', $e->getMessage());
200+
}
201+
}
181202
}

0 commit comments

Comments
 (0)