Skip to content

Commit

Permalink
Fix match of union of enums
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Jul 13, 2024
1 parent 2301b8b commit 44e40f0
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 8 deletions.
22 changes: 14 additions & 8 deletions src/Analyser/NodeScopeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -3446,14 +3446,20 @@ static function (Node $node, Scope $scope) use ($nodeCallback): void {
$expr->cond,
$enumCase,
);
} elseif (count($unusedIndexedEnumCases[$loweredFetchedClassName]) === 1) {
$hasAlwaysTrueCond = true;

// force "always true"
$armConditionScope = $armConditionScope->addTypeToExpression(
$expr->cond,
$enumCase,
);
} else {
$unusedCasesCount = 0;
foreach ($unusedIndexedEnumCases as $cases) {
$unusedCasesCount += count($cases);
}
if ($unusedCasesCount === 1) {
$hasAlwaysTrueCond = true;

// force "always true"
$armConditionScope = $armConditionScope->addTypeToExpression(
$expr->cond,
$enumCase,
);
}
}

$this->processExprNode($stmt, $cond, $armConditionScope, $nodeCallback, $deepContext);
Expand Down
9 changes: 9 additions & 0 deletions tests/PHPStan/Rules/Comparison/MatchExpressionRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -581,4 +581,13 @@ public function testBug9879(): void
$this->analyse([__DIR__ . '/data/bug-9879.php'], []);
}

public function testBug11313(): void
{
if (PHP_VERSION_ID < 80100) {
$this->markTestSkipped('Test requires PHP 8.1.');
}

$this->analyse([__DIR__ . '/data/bug-11313.php'], []);
}

}
23 changes: 23 additions & 0 deletions tests/PHPStan/Rules/Comparison/data/bug-11313.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php // lint >= 8.1

namespace Bug11313;

enum Foo: string
{
case CaseOne = 'one';
case CaseTwo = 'two';
}

enum Bar: string
{
case CaseThree = 'Three';
}

function test(Foo|Bar $union): bool
{
return match ($union) {
Bar::CaseThree,
Foo::CaseOne => true,
Foo::CaseTwo => false,
};
}

0 comments on commit 44e40f0

Please sign in to comment.