Skip to content

Commit

Permalink
[CodeQuality] Handle do { } while maybe returned on ExplicitReturnNul…
Browse files Browse the repository at this point in the history
…lRector (#5766)

* [CodeQuality] Handle do {} while maybe returned on ExplicitReturnNullRector

* handle possibly returned

* debug

* debug
  • Loading branch information
samsonasik committed Mar 23, 2024
1 parent aac889b commit 879feb8
Show file tree
Hide file tree
Showing 3 changed files with 95 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\ClassMethod\ExplicitReturnNullRector\Fixture;

final class DoWhileMaybeReturned
{
public function run(int $i)
{
do {
if (rand(0, 1)) {
continue;
}

return 2;
} while (++$i < 1);
}
}

?>
-----
<?php

namespace Rector\Tests\CodeQuality\Rector\ClassMethod\ExplicitReturnNullRector\Fixture;

final class DoWhileMaybeReturned
{
public function run(int $i)
{
do {
if (rand(0, 1)) {
continue;
}

return 2;
} while (++$i < 1);
return null;
}
}

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\ClassMethod\ExplicitReturnNullRector\Fixture;

final class DoWhileMaybeReturned2
{
public function run(int $i)
{
do {
if (rand(0,1)) {
break;
}

return 2;
} while (++$i < 1);
}
}

?>
-----
<?php

namespace Rector\Tests\CodeQuality\Rector\ClassMethod\ExplicitReturnNullRector\Fixture;

final class DoWhileMaybeReturned2
{
public function run(int $i)
{
do {
if (rand(0,1)) {
break;
}

return 2;
} while (++$i < 1);
return null;
}
}

?>
16 changes: 15 additions & 1 deletion rules/TypeDeclaration/TypeInferer/SilentVoidResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
use PhpParser\Node\Expr\YieldFrom;
use PhpParser\Node\FunctionLike;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Break_;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Continue_;
use PhpParser\Node\Stmt\Do_;
use PhpParser\Node\Stmt\Else_;
use PhpParser\Node\Stmt\Expression;
Expand Down Expand Up @@ -94,14 +96,26 @@ private function hasStmtsAlwaysReturnOrExit(array $stmts): bool
return true;
}

if ($stmt instanceof Do_ && $this->hasStmtsAlwaysReturnOrExit($stmt->stmts)) {
if ($stmt instanceof Do_ && $this->isDoWithAlwaysReturnOrExit($stmt)) {
return true;
}
}

return false;
}

private function isDoWithAlwaysReturnOrExit(Do_ $do): bool
{
if (! $this->hasStmtsAlwaysReturnOrExit($do->stmts)) {
return false;
}

return ! (bool) $this->betterNodeFinder->findFirst(
$do->stmts,
static fn (Node $node): bool => $node instanceof Break_ || $node instanceof Continue_
);
}

private function isIfReturn(Stmt|Expr $stmt): bool
{
if (! $stmt instanceof If_) {
Expand Down

0 comments on commit 879feb8

Please sign in to comment.