[Php80] Skip no default return fluent on ChangeSwitchToMatchRector (#2334)

This commit is contained in:
Abdul Malik Ikhsan 2022-05-19 23:23:22 +07:00 committed by GitHub
parent f90acd4c3a
commit 3f0a0b7259
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 50 additions and 5 deletions

View File

@ -0,0 +1,22 @@
<?php
namespace Rector\Tests\Php80\Rector\Switch_\ChangeSwitchToMatchRector\Fixture;
class SkipNoDefaultReturnFluent
{
private ?string $result = null;
public function run($value)
{
switch (strtolower($value)) {
case 'a':
$this->result = 0;
break;
case 'b':
$this->result = 1;
break;
}
return $this;
}
}

View File

@ -4,12 +4,16 @@ declare(strict_types=1);
namespace Rector\Php80\NodeAnalyzer;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\Match_;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\Return_;
use PhpParser\Node\Stmt\Switch_;
use PhpParser\Node\Stmt\Throw_;
use Rector\Core\PhpParser\Comparing\NodeComparator;
use Rector\NodeNameResolver\NodeNameResolver;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\Php80\Enum\MatchKind;
@ -20,6 +24,7 @@ final class MatchSwitchAnalyzer
public function __construct(
private readonly SwitchAnalyzer $switchAnalyzer,
private readonly NodeNameResolver $nodeNameResolver,
private readonly NodeComparator $nodeComparator
) {
}
@ -120,17 +125,35 @@ final class MatchSwitchAnalyzer
private function isNextStmtReturnWithExpr(Switch_ $switch): bool
{
$parent = $switch->getAttribute(AttributeKey::NEXT_NODE);
if (! $parent instanceof Return_) {
$next = $switch->getAttribute(AttributeKey::NEXT_NODE);
if (! $next instanceof Return_) {
return false;
}
return $parent->expr !== null;
if (! $next->expr instanceof Expr) {
return false;
}
foreach ($switch->cases as $case) {
/** @var Expression[] $expressions */
$expressions = array_filter($case->stmts, fn (Node $node): bool => $node instanceof Expression);
foreach ($expressions as $expression) {
if (! $expression->expr instanceof Assign) {
continue;
}
if (! $this->nodeComparator->areNodesEqual($expression->expr->var, $next->expr)) {
return false;
}
}
}
return true;
}
private function isNextStmtThrows(Switch_ $switch): bool
{
$parent = $switch->getAttribute(AttributeKey::NEXT_NODE);
return $parent instanceof Throw_;
$next = $switch->getAttribute(AttributeKey::NEXT_NODE);
return $next instanceof Throw_;
}
}