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

This file was deleted.

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

namespace Rector\Tests\Php80\Rector\Switch_\ChangeSwitchToMatchRector\Fixture;

/**
* switch compares loosely, "777abc" == 777 is false,
* but match ((int) "777abc") would hit the 777 arm
*/
final class SkipCastIntForString
{
function test(string $code): int
{
switch($code) {
case 777:
return 1;
case 88:
return 2;
default:
return 4;
};
}
}
39 changes: 29 additions & 10 deletions rules/Php80/Rector/Switch_/ChangeSwitchToMatchRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\Cast;
use PhpParser\Node\Expr\Cast\Int_;
use PhpParser\Node\Expr\Cast\String_;
use PhpParser\Node\Expr\Match_;
use PhpParser\Node\Stmt\Expression;
Expand Down Expand Up @@ -124,6 +123,12 @@ public function refactor(Node $node): null|Node
}

$match = $matchResult->getMatch();

// (int) cast would turn loose "777abc" == 777 (false) into 777 === 777 (true)
if ($this->isStringCondWithIntArm($match)) {
continue;
}

if ($matchResult->shouldRemoveNextStmt() && $isReturn) {
unset($node->stmts[$key + 1]);
}
Expand Down Expand Up @@ -180,12 +185,7 @@ public function provideMinPhpVersion(): int
private function castMatchCond(Match_ $match): void
{
$type = $this->nodeTypeResolver->getNativeType($match->cond);
$isNativeCondString = $type->isString()
->yes();
$isNativeCondInt = $type->isInteger()
->yes();

if (! $isNativeCondString && ! $isNativeCondInt) {
if (! $type->isInteger()->yes()) {
return;
}

Expand All @@ -199,9 +199,7 @@ private function castMatchCond(Match_ $match): void

foreach ($arm->conds as $armCond) {
$armCondType = $this->nodeTypeResolver->getNativeType($armCond);
if ($armCondType->isInteger()->yes() && $isNativeCondString) {
$newMatchCond = new Int_($match->cond);
} elseif ($armCondType->isString()->yes() && $isNativeCondInt) {
if ($armCondType->isString()->yes()) {
$newMatchCond = new String_($match->cond);
} else {
$newMatchCond = null;
Expand All @@ -215,6 +213,27 @@ private function castMatchCond(Match_ $match): void
}
}

private function isStringCondWithIntArm(Match_ $match): bool
{
if (! $this->nodeTypeResolver->getNativeType($match->cond)->isString()->yes()) {
return false;
}

foreach ($match->arms as $arm) {
if ($arm->conds === null) {
continue;
}

foreach ($arm->conds as $armCond) {
if ($this->nodeTypeResolver->getNativeType($armCond)->isInteger()->yes()) {
return true;
}
}
}

return false;
}

private function mirrorDynamicBoolExpr(Match_ $match): void
{
// switch(true) already just use
Expand Down
Loading