Skip to content

Commit

Permalink
Add ReturnTypeFromStrictBoolReturnExprRector support for if/else returns
Browse files Browse the repository at this point in the history
  • Loading branch information
TomasVotruba committed Dec 23, 2023
1 parent 62a6032 commit fc0bd40
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromStrictBoolReturnExprRector\Fixture;

final class IfElseBools
{
public function run($value)
{
if ($value) {
return true;
} else {
return false;
}
}
}

?>
-----
<?php

namespace Rector\Tests\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromStrictBoolReturnExprRector\Fixture;

final class IfElseBools
{
public function run($value): bool
{
if ($value) {
return true;
} else {
return false;
}
}
}

?>
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
use PhpParser\Node\Expr\Closure;
use PhpParser\Node\Expr\Yield_;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Else_;
use PhpParser\Node\Stmt\Function_;
use PhpParser\Node\Stmt\If_;
use PhpParser\Node\Stmt\Return_;
use Rector\Core\PhpParser\Node\BetterNodeFinder;
use Rector\TypeDeclaration\NodeAnalyzer\ReturnAnalyzer;
Expand Down Expand Up @@ -44,11 +46,30 @@ public function matchAlwaysStrictReturns(ClassMethod|Closure|Function_ $function
return [];
}

// is one in ifOrElse, other in else?
$onlyStmt = $functionLike->stmts[0] ?? null;
if ($onlyStmt instanceof If_ && $onlyStmt->elseifs === [] && $onlyStmt->else instanceof Else_) {
if ($this->hasFirstLevelReturn($onlyStmt) && $this->hasFirstLevelReturn($onlyStmt->else)) {
return $returns;
}
}

// has root return?
if (! $this->returnAnalyzer->hasClassMethodRootReturn($functionLike)) {
return [];
}

return $returns;
}

private function hasFirstLevelReturn(If_|Else_ $ifOrElse): bool
{
foreach ($ifOrElse->stmts as $stmt) {
if ($stmt instanceof Return_) {
return true;
}
}

return false;
}
}

0 comments on commit fc0bd40

Please sign in to comment.