Skip to content

Commit 9d19f30

Browse files
committed
fix has_method('__toString') coercison
1 parent d338a47 commit 9d19f30

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

src/Type/Traits/ObjectTypeTrait.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
use PHPStan\Type\MixedType;
2222
use PHPStan\Type\StringType;
2323
use PHPStan\Type\Type;
24+
use PHPStan\Type\TypeCombinator;
2425

2526
trait ObjectTypeTrait
2627
{
@@ -275,6 +276,10 @@ public function toArrayKey(): Type
275276

276277
public function toCoercedArgumentType(bool $strictTypes): Type
277278
{
279+
if (!$strictTypes) {
280+
return TypeCombinator::union($this, $this->toString());
281+
}
282+
278283
return $this;
279284
}
280285

tests/PHPStan/Analyser/nsrt/bug-12393b.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -571,3 +571,17 @@ public function __toString(): string {
571571
return 'Foo';
572572
}
573573
}
574+
575+
class ObjectWithToStringMethod {
576+
private string $foo;
577+
578+
public function doFoo(object $foo): void {
579+
if (method_exists($foo, '__toString')) {
580+
$this->foo = $foo;
581+
assertType('string', $this->foo);
582+
}
583+
}
584+
public function __toString(): string {
585+
return 'Foo';
586+
}
587+
}

0 commit comments

Comments
 (0)