Skip to content

Commit 9de9efa

Browse files
committed
StringAlwaysAcceptingObjectWithToStringType is supertype of Stringable objects
1 parent 824cb02 commit 9de9efa

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

src/Type/StringAlwaysAcceptingObjectWithToStringType.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,36 @@
33
namespace PHPStan\Type;
44

55
use PHPStan\Reflection\ReflectionProviderStaticAccessor;
6+
use PHPStan\TrinaryLogic;
67

78
class StringAlwaysAcceptingObjectWithToStringType extends StringType
89
{
910

11+
public function isSuperTypeOf(Type $type): TrinaryLogic
12+
{
13+
if ($type instanceof CompoundType) {
14+
return $type->isSubTypeOf($this);
15+
}
16+
17+
$thatClassNames = $type->getObjectClassNames();
18+
if ($thatClassNames === []) {
19+
return parent::isSuperTypeOf($type);
20+
}
21+
22+
$result = TrinaryLogic::createNo();
23+
$reflectionProvider = ReflectionProviderStaticAccessor::getInstance();
24+
foreach ($thatClassNames as $thatClassName) {
25+
if (!$reflectionProvider->hasClass($thatClassName)) {
26+
return TrinaryLogic::createNo();
27+
}
28+
29+
$typeClass = $reflectionProvider->getClass($thatClassName);
30+
$result = $result->or(TrinaryLogic::createFromBoolean($typeClass->hasNativeMethod('__toString')));
31+
}
32+
33+
return $result;
34+
}
35+
1036
public function acceptsWithReason(Type $type, bool $strictTypes): AcceptsResult
1137
{
1238
$thatClassNames = $type->getObjectClassNames();

tests/PHPStan/Type/StringTypeTest.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,11 @@ public function dataIsSuperTypeOf(): array
8686
new GenericClassStringType(new ObjectType(stdClass::class)),
8787
TrinaryLogic::createMaybe(),
8888
],
89+
[
90+
new StringAlwaysAcceptingObjectWithToStringType(),
91+
new ObjectType(ClassWithToString::class),
92+
TrinaryLogic::createYes(),
93+
],
8994
];
9095
}
9196

0 commit comments

Comments
 (0)