Skip to content

Commit 010e843

Browse files
authored
[TypeDeclaration] Map accessory string intersection to string in union return type (#8125)
ReturnUnionTypeRector inferred 0|(numeric-string&non-falsy-string) returns but IntersectionTypeMapper only handled object intersections, returning null for the string-accessory member and aborting the whole union. Map a pure-string intersection to string so int|string is added.
1 parent 7392d63 commit 010e843

2 files changed

Lines changed: 63 additions & 0 deletions

File tree

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
<?php
2+
3+
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnUnionTypeRector\Fixture;
4+
5+
final class IntOrNumericString
6+
{
7+
private function getAssetSize(): int
8+
{
9+
return 1000;
10+
}
11+
12+
public function getTotalFilesize($assets)
13+
{
14+
if (empty($assets)) {
15+
return 0;
16+
}
17+
18+
$size = $this->getAssetSize($assets);
19+
20+
if ($size) {
21+
$size = (string) $size;
22+
}
23+
24+
return $size;
25+
}
26+
}
27+
28+
?>
29+
-----
30+
<?php
31+
32+
namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnUnionTypeRector\Fixture;
33+
34+
final class IntOrNumericString
35+
{
36+
private function getAssetSize(): int
37+
{
38+
return 1000;
39+
}
40+
41+
public function getTotalFilesize($assets): int|string
42+
{
43+
if (empty($assets)) {
44+
return 0;
45+
}
46+
47+
$size = $this->getAssetSize($assets);
48+
49+
if ($size) {
50+
$size = (string) $size;
51+
}
52+
53+
return $size;
54+
}
55+
}
56+
57+
?>

‎src/PHPStanStaticTypeMapper/TypeMapper/IntersectionTypeMapper.php‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
namespace Rector\PHPStanStaticTypeMapper\TypeMapper;
66

77
use PhpParser\Node;
8+
use PhpParser\Node\Identifier;
89
use PhpParser\Node\Name\FullyQualified;
910
use PHPStan\PhpDocParser\Ast\Node as AstNode;
1011
use PHPStan\PhpDocParser\Ast\Type\ArrayShapeItemNode;
@@ -91,6 +92,11 @@ function (AstNode $astNode): int|IdentifierTypeNode {
9192
*/
9293
public function mapToPhpParserNode(Type $type, string $typeKind): ?Node
9394
{
95+
// accessory string types, e.g. "numeric-string&non-falsy-string", are just "string"
96+
if ($type->isString()->yes()) {
97+
return new Identifier('string');
98+
}
99+
94100
if (! $this->phpVersionProvider->isAtLeastPhpVersion(PhpVersionFeature::INTERSECTION_TYPES)) {
95101
return null;
96102
}

0 commit comments

Comments
 (0)