Skip to content

Commit

Permalink
Arrow functions - allow more precise return type even when native ret…
Browse files Browse the repository at this point in the history
…urn type is present
  • Loading branch information
ondrejmirtes committed Dec 22, 2020
1 parent 94e3443 commit 3d0ac6f
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 3 deletions.
6 changes: 5 additions & 1 deletion src/Analyser/MutatingScope.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@
use PHPStan\Type\ThisType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\TypehintHelper;
use PHPStan\Type\TypeTraverser;
use PHPStan\Type\TypeUtils;
use PHPStan\Type\TypeWithClassName;
Expand Down Expand Up @@ -1306,8 +1307,11 @@ private function resolveType(Expr $node): Type
);
}

if ($node->returnType === null && $node instanceof Expr\ArrowFunction) {
if ($node instanceof Expr\ArrowFunction) {
$returnType = $this->getType($node->expr);
if ($node->returnType !== null) {
$returnType = TypehintHelper::decideType($this->getFunctionType($node->returnType, false, false), $returnType);
}
} else {
$returnType = $this->getFunctionType($node->returnType, $node->returnType === null, false);
}
Expand Down
8 changes: 6 additions & 2 deletions tests/PHPStan/Analyser/NodeScopeResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10915,13 +10915,17 @@ public function dataArrowFunctions(): array
{
return [
[
'Closure(string): int',
'Closure(string): 1',
'$x',
],
[
'int',
'1',
'$x()',
],
[
'array(\'a\' => 1, \'b\' => 2)',
'$y()',
],
];
}

Expand Down
1 change: 1 addition & 0 deletions tests/PHPStan/Analyser/data/arrow-functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ class Foo
public function doFoo()
{
$x = fn(string $str): int => 1;
$y = fn(): array => ['a' => 1, 'b' => 2];
die;
}

Expand Down

0 comments on commit 3d0ac6f

Please sign in to comment.