Skip to content

Commit

Permalink
Solve issues with arrow functions containing void expression
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Dec 29, 2020
1 parent 143741c commit 7ac6383
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/Analyser/NodeScopeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -1843,7 +1843,7 @@ static function () use ($scope, $expr): MutatingScope {

$arrowFunctionScope = $scope->enterArrowFunction($expr);
$nodeCallback(new InArrowFunctionNode($expr), $arrowFunctionScope);
$this->processExprNode($expr->expr, $arrowFunctionScope, $nodeCallback, $context);
$this->processExprNode($expr->expr, $arrowFunctionScope, $nodeCallback, ExpressionContext::createTopLevel());
$hasYield = false;

} elseif ($expr instanceof ErrorSuppress) {
Expand Down
9 changes: 8 additions & 1 deletion src/Rules/Functions/ArrowFunctionReturnTypeRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use PHPStan\Node\InArrowFunctionNode;
use PHPStan\Rules\FunctionReturnTypeCheck;
use PHPStan\Type\ObjectType;
use PHPStan\Type\VoidType;

/**
* @implements \PHPStan\Rules\Rule<\PHPStan\Node\InArrowFunctionNode>
Expand Down Expand Up @@ -36,10 +37,16 @@ public function processNode(Node $node, Scope $scope): array
$returnType = $scope->getAnonymousFunctionReturnType();
$generatorType = new ObjectType(\Generator::class);

$originalNode = $node->getOriginalNode();
$isVoidSuperType = (new VoidType())->isSuperTypeOf($returnType);
if ($originalNode->returnType === null && $isVoidSuperType->yes()) {
return [];
}

return $this->returnTypeCheck->checkReturnType(
$scope,
$returnType,
$node->getOriginalNode()->expr,
$originalNode->expr,
'Anonymous function should return %s but empty return statement found.',
'Anonymous function with return type void returns %s but should not return anything.',
'Anonymous function should return %s but returns %s.',
Expand Down
15 changes: 15 additions & 0 deletions tests/PHPStan/Rules/Functions/data/arrow-functions-return-type.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,18 @@ public function doFoo(int $i)
}

}

class Bar
{

public function doFoo(): void
{

}

public function doBar(): void
{
fn () => $this->doFoo();
}

}
20 changes: 20 additions & 0 deletions tests/PHPStan/Rules/Methods/data/arrow-function-bind.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,23 @@ public function fooMethod(): Foo
}

}

class BazVoid
{

public function doFoo(): void
{

}

public function doBar(): void
{
$this->doBaz(fn () => $this->doFoo());
}

public function doBaz(callable $cb): void
{

}

}

0 comments on commit 7ac6383

Please sign in to comment.