Skip to content

Commit

Permalink
StrictComparisonOfDifferentTypesRule - do not report "use match inste…
Browse files Browse the repository at this point in the history
…ad" when already in match
  • Loading branch information
ondrejmirtes committed Apr 4, 2023
1 parent 497835e commit 9850ea7
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 2 deletions.
5 changes: 4 additions & 1 deletion src/Parser/LastConditionVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ class LastConditionVisitor extends NodeVisitorAbstract
{

public const ATTRIBUTE_NAME = 'isLastCondition';
public const ATTRIBUTE_IS_MATCH_NAME = 'isMatch';

public function enterNode(Node $node): ?Node
{
Expand All @@ -31,7 +32,9 @@ public function enterNode(Node $node): ?Node
}

$isLast = $i === $lastArm;
$arm->conds[count($arm->conds) - 1]->setAttribute(self::ATTRIBUTE_NAME, $isLast);
$index = count($arm->conds) - 1;
$arm->conds[$index]->setAttribute(self::ATTRIBUTE_NAME, $isLast);
$arm->conds[$index]->setAttribute(self::ATTRIBUTE_IS_MATCH_NAME, true);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,11 @@ public function processNode(Node $node, Scope $scope): array
$errorBuilder->addTip('Remove remaining cases below this one and this error will disappear too.');
}

if ($leftType->isEnum()->yes() && $rightType->isEnum()->yes()) {
if (
$leftType->isEnum()->yes()
&& $rightType->isEnum()->yes()
&& $node->getAttribute(LastConditionVisitor::ATTRIBUTE_IS_MATCH_NAME, false) !== true
) {
$errorBuilder->addTip('Use match expression instead. PHPStan will report unhandled enum cases.');
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -955,6 +955,11 @@ public function testEnumTips(): void
29,
'Use match expression instead. PHPStan will report unhandled enum cases.',
],
[
'Strict comparison using === between StrictComparisonEnumTips\SomeEnum::Two and StrictComparisonEnumTips\SomeEnum::Two will always evaluate to true.',
50,
'Remove remaining cases below this one and this error will disappear too.',
],
]);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,23 @@ public function exhaustiveWithSafetyCheck2(): int
throw new \LogicException('New case added, handling missing');
}

public function exhaustiveWithSafetyCheckInMatchAlready(): int
{
// not reported by this rule at all
return match ($this) {
self::One => -1,
self::Two => 0,
default => throw new \LogicException('New case added, handling missing'),
};
}

public function exhaustiveWithSafetyCheckInMatchAlready2(self $self): int
{
return match (true) {
$self === self::One => -1,
$self === self::Two => 0,
default => throw new \LogicException('New case added, handling missing'),
};
}

}

0 comments on commit 9850ea7

Please sign in to comment.