From 3d0ac6f15e4477480295331f72631067e6bc99c0 Mon Sep 17 00:00:00 2001 From: Ondrej Mirtes Date: Tue, 22 Dec 2020 14:18:21 +0100 Subject: [PATCH] Arrow functions - allow more precise return type even when native return type is present --- src/Analyser/MutatingScope.php | 6 +++++- tests/PHPStan/Analyser/NodeScopeResolverTest.php | 8 ++++++-- tests/PHPStan/Analyser/data/arrow-functions.php | 1 + 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/Analyser/MutatingScope.php b/src/Analyser/MutatingScope.php index 501588eaf5..a87dc9e1f7 100644 --- a/src/Analyser/MutatingScope.php +++ b/src/Analyser/MutatingScope.php @@ -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; @@ -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); } diff --git a/tests/PHPStan/Analyser/NodeScopeResolverTest.php b/tests/PHPStan/Analyser/NodeScopeResolverTest.php index a96fd1a59e..e097c3d8e7 100644 --- a/tests/PHPStan/Analyser/NodeScopeResolverTest.php +++ b/tests/PHPStan/Analyser/NodeScopeResolverTest.php @@ -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()', + ], ]; } diff --git a/tests/PHPStan/Analyser/data/arrow-functions.php b/tests/PHPStan/Analyser/data/arrow-functions.php index 2e9bc13ffb..0a94933360 100644 --- a/tests/PHPStan/Analyser/data/arrow-functions.php +++ b/tests/PHPStan/Analyser/data/arrow-functions.php @@ -8,6 +8,7 @@ class Foo public function doFoo() { $x = fn(string $str): int => 1; + $y = fn(): array => ['a' => 1, 'b' => 2]; die; }