From c258109844f4875f43d6f7ed10f602ef12915434 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Th=C3=A9o=20FIDRY?= Date: Sat, 7 Jul 2018 22:55:53 +0200 Subject: [PATCH] Allow stringeable objects to be serialized by StringType Closes #302 --- src/Type/Definition/StringType.php | 3 +++ tests/Type/ScalarSerializationTest.php | 1 + 2 files changed, 4 insertions(+) diff --git a/src/Type/Definition/StringType.php b/src/Type/Definition/StringType.php index 8de4063..cabd344 100644 --- a/src/Type/Definition/StringType.php +++ b/src/Type/Definition/StringType.php @@ -40,6 +40,9 @@ represent free-form human-readable text.'; if ($value === null) { return 'null'; } + if (is_object($value) && method_exists($value, '__toString')) { + return (string) $value; + } if (!is_scalar($value)) { throw new Error("String cannot represent non scalar value: " . Utils::printSafe($value)); } diff --git a/tests/Type/ScalarSerializationTest.php b/tests/Type/ScalarSerializationTest.php index 8fdd0d6..8b42d55 100644 --- a/tests/Type/ScalarSerializationTest.php +++ b/tests/Type/ScalarSerializationTest.php @@ -150,6 +150,7 @@ class ScalarSerializationTest extends \PHPUnit_Framework_TestCase $this->assertSame('true', $stringType->serialize(true)); $this->assertSame('false', $stringType->serialize(false)); $this->assertSame('null', $stringType->serialize(null)); + $this->assertSame('2', $stringType->serialize(new ObjectIdStub(2))); } public function testSerializesOutputStringsCannotRepresentArray()