Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

namespace Rector\Tests\Php84\Rector\Foreach_\ForeachToArrayAnyRector\Fixture;

class EarlyReturnSkipIfWithElseIfElse
{
public function run($host, array $noProxyArray)
{
foreach ($noProxyArray as $area) {
if ($area === '*') {
return true;
} elseif (empty($area)) {
continue;
} elseif ($area === $host) {
return true;
} else {
$area = '.' . ltrim($area, '.');
if (substr($host, -(strlen($area))) === $area) {
return true;
}
}
}

return false;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace Rector\Tests\Php84\Rector\Foreach_\ForeachToArrayAnyRector\Fixture;

class SkipBooleanIfWithElse
{
public function run(array $animals)
{
$found = false;
foreach ($animals as $animal) {
if (str_starts_with($animal, 'c')) {
$found = true;
break;
} else {
$found = false;
}
}
return $found;
}
}
9 changes: 9 additions & 0 deletions rules/Php84/Rector/Foreach_/ForeachToArrayAnyRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Param;
use PhpParser\Node\Stmt\Break_;
use PhpParser\Node\Stmt\Else_;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\Foreach_;
use PhpParser\Node\Stmt\If_;
Expand Down Expand Up @@ -277,6 +278,10 @@ private function isValidBooleanAssignmentForeachStructure(Foreach_ $foreach, Var
return false;
}

if ($firstStmt->elseifs !== [] || $firstStmt->else instanceof Else_) {
return false;
}

$assignmentStmt = $firstStmt->stmts[0];
$breakStmt = $firstStmt->stmts[1];

Expand Down Expand Up @@ -315,6 +320,10 @@ private function isValidEarlyReturnForeachStructure(Foreach_ $foreach): bool

$ifStmt = $foreach->stmts[0];

if ($ifStmt->elseifs !== [] || $ifStmt->else instanceof Else_) {
return false;
}

if (count($ifStmt->stmts) !== 1) {
return false;
}
Expand Down
Loading