Skip to content

[Php80] Skip loose comparison change in ChangeSwitchToMatchRector - #9065

Merged
TomasVotruba merged 1 commit into
mainfrom
fix-switch-match-cast
Nov 25, 2026
Merged

TomasVotruba merged 1 commit into
mainfrom
fix-switch-match-cast

Conversation

@TomasVotruba

Copy link
Copy Markdown
Member

switch compares with loose ==, match with strict ===. Two places where the conversion changed which arm matches:

1. (string) cast decided by the last arm only

/** @param string $other */
public function run(int $code, $other): string
{
    switch ($code) {
        case '2':
            return 'two';
        case $other:
            return 'other';
        default:
            return 'default';
    }
}

Rector produced match ($code) { '2' => 'two', ... } - no cast, because the break in castMatchCond() only left the inner loop and the next arm overwrote the decision. 2 === '2' is false, so 'two' is never returned. With the arms in the other order the cast is added, and then non-string arms break instead.

Numeric strings that are not a canonical int had the same problem: case '01' became (string) $code === '01', while 1 == '01' is true.

2. Untyped subject with string cases

public function run($value): string
{
    switch ($value) {
        case 'a':
            return 'first';
        case '1':
            return 'second';
        default:
            return 'other';
    }
}

became match ($value) { 'a' => ..., '1' => ... }. With unknown $value, true == 'a' and 1 == '1' match the switch, but not the match.

Fix

isLooseComparisonChanged() replaces isStringCondWithIntArm() and skips the conversion when:

castMatchCond() now only adds the (string) cast when every arm is a string.

Fixtures

6 existing fixtures converted an untyped subject with string cases. They test other things (default position, comments, next stmt), so I typed their subject as string to keep that coverage, and added skip_untyped_subject_with_string_cases.php.inc for the untyped case. Plus skip_cast_string_for_int_with_mixed_arms.php.inc and skip_cast_string_for_int_with_numeric_string.php.inc. All 3 new fixtures fail on main.

@TomasVotruba
TomasVotruba merged commit 8891154 into main Nov 25, 2026
51 checks passed
@TomasVotruba
TomasVotruba deleted the fix-switch-match-cast branch November 25, 2026 13:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant