Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow objects with __toString in IDType #210

Merged
merged 2 commits into from
Dec 12, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/Type/Definition/IDType.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public function serialize($value)
if ($value === null) {
return 'null';
}
if (!is_scalar($value)) {
if (!is_scalar($value) && (!is_object($value) || !method_exists($value, '__toString'))) {
throw new InvariantViolation("ID type cannot represent non scalar value: " . Utils::printSafe($value));
}
return (string) $value;
Expand Down
23 changes: 23 additions & 0 deletions tests/Type/ObjectIdStub.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php
namespace GraphQL\Tests\Type;

class ObjectIdStub
{
/**
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is it expected to have tabs here?

* @var int
*/
private $id;

/**
* @param int $id
*/
public function __construct($id)
{
$this->id = $id;
}

public function __toString()
{
return (string) $this->id;
}
}
21 changes: 21 additions & 0 deletions tests/Type/ScalarSerializationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -178,4 +178,25 @@ public function testSerializesOutputBoolean()

// TODO: how should it behave on '0'?
}

public function testSerializesOutputID()
{
$idType = Type::id();

$this->assertSame('string', $idType->serialize('string'));
$this->assertSame('', $idType->serialize(''));
$this->assertSame('1', $idType->serialize('1'));
$this->assertSame('1', $idType->serialize(1));
$this->assertSame('0', $idType->serialize(0));
$this->assertSame('true', $idType->serialize(true));
$this->assertSame('false', $idType->serialize(false));
$this->assertSame('2', $idType->serialize(new ObjectIdStub(2)));

try {
$idType->serialize(new \stdClass());
$this->fail('Expected exception was not thrown');
} catch (InvariantViolation $e) {
$this->assertEquals('ID type cannot represent non scalar value: instance of stdClass', $e->getMessage());
}
}
}