Skip to content

Commit 2e280c1

Browse files
committed
added stringable objects as a possible parameter
1 parent 264893c commit 2e280c1

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

src/ParameterHelper.php

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,22 @@ public static function asParameter($value)
4141
return self::emptySequenceToArray($value) ??
4242
self::emptyDictionaryToStdClass($value) ??
4343
self::filledIterableToArray($value) ??
44+
self::stringableToString($value) ??
4445
self::filterInvalidType($value);
4546
}
4647

48+
/**
49+
* @param mixed $value
50+
*/
51+
private static function stringableToString($value): ?string
52+
{
53+
if (is_object($value) && method_exists($value, '__toString')) {
54+
return (string) $value;
55+
}
56+
57+
return null;
58+
}
59+
4760
/**
4861
* @param mixed $value
4962
*
@@ -52,7 +65,7 @@ public static function asParameter($value)
5265
private static function filterInvalidType($value)
5366
{
5467
if ($value !== null && !is_scalar($value)) {
55-
throw new InvalidArgumentException('Parameters must be iterable, scalar or null');
68+
throw new InvalidArgumentException('Parameters must be iterable, scalar, null or stringable');
5669
}
5770

5871
return $value;

tests/Unit/ParameterHelperTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,4 +135,15 @@ public function testAsParmeterEmptyArray(): void
135135
$result = ParameterHelper::asParameter([]);
136136
self::assertInstanceOf(stdClass::class, $result);
137137
}
138+
139+
public function testStringable(): void
140+
{
141+
$result = ParameterHelper::asParameter(new class() {
142+
public function __toString(): string
143+
{
144+
return 'abc';
145+
}
146+
});
147+
self::assertEquals('abc', $result);
148+
}
138149
}

0 commit comments

Comments
 (0)