Skip to content

Commit 3d0ac6f

Browse files
committed
Arrow functions - allow more precise return type even when native return type is present
1 parent 94e3443 commit 3d0ac6f

File tree

3 files changed

+12
-3
lines changed

3 files changed

+12
-3
lines changed

src/Analyser/MutatingScope.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@
8080
use PHPStan\Type\ThisType;
8181
use PHPStan\Type\Type;
8282
use PHPStan\Type\TypeCombinator;
83+
use PHPStan\Type\TypehintHelper;
8384
use PHPStan\Type\TypeTraverser;
8485
use PHPStan\Type\TypeUtils;
8586
use PHPStan\Type\TypeWithClassName;
@@ -1306,8 +1307,11 @@ private function resolveType(Expr $node): Type
13061307
);
13071308
}
13081309

1309-
if ($node->returnType === null && $node instanceof Expr\ArrowFunction) {
1310+
if ($node instanceof Expr\ArrowFunction) {
13101311
$returnType = $this->getType($node->expr);
1312+
if ($node->returnType !== null) {
1313+
$returnType = TypehintHelper::decideType($this->getFunctionType($node->returnType, false, false), $returnType);
1314+
}
13111315
} else {
13121316
$returnType = $this->getFunctionType($node->returnType, $node->returnType === null, false);
13131317
}

tests/PHPStan/Analyser/NodeScopeResolverTest.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10915,13 +10915,17 @@ public function dataArrowFunctions(): array
1091510915
{
1091610916
return [
1091710917
[
10918-
'Closure(string): int',
10918+
'Closure(string): 1',
1091910919
'$x',
1092010920
],
1092110921
[
10922-
'int',
10922+
'1',
1092310923
'$x()',
1092410924
],
10925+
[
10926+
'array(\'a\' => 1, \'b\' => 2)',
10927+
'$y()',
10928+
],
1092510929
];
1092610930
}
1092710931

tests/PHPStan/Analyser/data/arrow-functions.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ class Foo
88
public function doFoo()
99
{
1010
$x = fn(string $str): int => 1;
11+
$y = fn(): array => ['a' => 1, 'b' => 2];
1112
die;
1213
}
1314

0 commit comments

Comments
 (0)