Skip to content

Commit

Permalink
ForbidUselessNullableReturn: proper closure support (#99)
Browse files Browse the repository at this point in the history
  • Loading branch information
janedbal committed Apr 5, 2023
1 parent a934cbf commit 7d51a4e
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -458,7 +458,7 @@ function example(MyClass $class) {
```

### forbidUselessNullableReturn
- Denies marking function/method return type as nullable when null is never returned
- Denies marking closure/function/method return type as nullable when null is never returned
- Recommended to be used together with `uselessPrivatePropertyDefaultValue` and `UselessPrivatePropertyNullabilityRule`
```php
public function example(int $foo): ?int { // null never returned
Expand Down
9 changes: 6 additions & 3 deletions src/Rule/ForbidUselessNullableReturnRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Node\ClosureReturnStatementsNode;
use PHPStan\Node\ReturnStatementsNode;
use PHPStan\Reflection\ParametersAcceptorSelector;
use PHPStan\Rules\Rule;
Expand Down Expand Up @@ -33,12 +34,14 @@ public function processNode(Node $node, Scope $scope): array
$verbosity = VerbosityLevel::precise();
$methodReflection = $scope->getFunction();

if ($methodReflection === null) {
if ($node instanceof ClosureReturnStatementsNode) { // @phpstan-ignore-line ignore bc promise
$declaredType = $scope->getFunctionType($node->getClosureExpr()->getReturnType(), false, false);
} elseif ($methodReflection !== null) {
$declaredType = ParametersAcceptorSelector::selectSingle($methodReflection->getVariants())->getReturnType();
} else {
return [];
}

$declaredType = ParametersAcceptorSelector::selectSingle($methodReflection->getVariants())->getReturnType();

if ($declaredType->isVoid()->yes()) {
return [];
}
Expand Down
15 changes: 15 additions & 0 deletions tests/Rule/data/ForbidUselessNullableReturnRule/code.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,24 @@ public function getStrict3(): int
return $this->bar;
}


public function voidMethod(): void
{
$fn = static function (array $string): ?array { // error: Declared return type array|null contains null, but it is never returned. Returned types: array.
return $string;
};

return;
}


}

function nullableFunction(int $int): ?int // error: Declared return type int|null contains null, but it is never returned. Returned types: int.
{
return $int;
}

$globalFn = static function (int $int): ?int { // error: Declared return type int|null contains null, but it is never returned. Returned types: int.
return $int;
};

0 comments on commit 7d51a4e

Please sign in to comment.