Skip to content

Commit

Permalink
[Php80] Skip no default return fluent on ChangeSwitchToMatchRector (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
samsonasik committed May 19, 2022
1 parent f90acd4 commit 3f0a0b7
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -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;
}
}
33 changes: 28 additions & 5 deletions rules/Php80/NodeAnalyzer/MatchSwitchAnalyzer.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,16 @@

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;
Expand All @@ -20,6 +24,7 @@ final class MatchSwitchAnalyzer
public function __construct(
private readonly SwitchAnalyzer $switchAnalyzer,
private readonly NodeNameResolver $nodeNameResolver,
private readonly NodeComparator $nodeComparator
) {
}

Expand Down Expand Up @@ -120,17 +125,35 @@ private function resolveUniqueKindsWithoutThrows(array $condAndExprs): array

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_;
}
}

0 comments on commit 3f0a0b7

Please sign in to comment.