Skip to content

Commit

Permalink
Serialize any stringable object
Browse files Browse the repository at this point in the history
  • Loading branch information
gapple committed Dec 4, 2020
1 parent bb4a82b commit e116ff3
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
8 changes: 4 additions & 4 deletions src/Serializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,14 +77,14 @@ private static function serializeBareItem($value): string
return self::serializeInteger($value);
} elseif (is_float($value)) {
return self::serializeDecimal($value);
} elseif (is_string($value)) {
return self::serializeString($value);
} elseif ($value instanceof Token) {
return self::serializeToken($value);
} elseif (is_bool($value)) {
return self::serializeBoolean($value);
} elseif ($value instanceof Token) {
return self::serializeToken($value);
} elseif ($value instanceof Bytes) {
return self::serializeByteSequence($value);
} elseif (is_string($value) || (is_object($value) && method_exists($value, '__toString'))) {
return self::serializeString($value);
}

throw new SerializeException("Unrecognized type");
Expand Down
28 changes: 28 additions & 0 deletions tests/SerializeStringTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,35 @@ class SerializeStringTest extends TestCase
public function testInvalidCharacter()
{
$this->expectException(SerializeException::class);
$this->expectExceptionMessage("Invalid characters in string");

Serializer::serializeItem("🙁");
}

public function testStringableObject()
{
$stringable = new class {
public function __toString(): string
{
return "Don't Panic";
}
};

$this->assertEquals('"Don\'t Panic"', Serializer::serializeItem($stringable));
}

public function testInvalidStringableObject()
{
$this->expectException(SerializeException::class);
$this->expectExceptionMessage("Invalid characters in string");

$stringable = new class {
public function __toString(): string
{
return "🙁";
}
};

Serializer::serializeItem($stringable);
}
}

0 comments on commit e116ff3

Please sign in to comment.