Error Identifier: match.unhandled
Every error reported by PHPStan has an error identifier. Here’s a list of all error identifiers. In PHPStan Pro you can see the error identifier next to each error and filter errors by their identifiers.
Code example #
<?php declare(strict_types = 1);
enum Suit
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
}
function suitToColor(Suit $suit): string
{
return match ($suit) {
Suit::Hearts, Suit::Diamonds => 'red',
Suit::Clubs => 'black',
};
}
Why is it reported? #
The match expression does not cover all possible values of the subject type. PHP throws an \UnhandledMatchError at runtime when no match arm matches the subject value.
In the example above, the Suit::Spades case is not handled, so passing it to suitToColor() would cause a runtime error.
How to fix it #
Add the missing match arms to handle all possible values:
return match ($suit) {
Suit::Hearts, Suit::Diamonds => 'red',
Suit::Clubs => 'black',
+ Suit::Spades => 'black',
};
Alternatively, add a default arm to catch any remaining values:
return match ($suit) {
Suit::Hearts, Suit::Diamonds => 'red',
- Suit::Clubs => 'black',
+ Suit::Clubs, Suit::Spades => 'black',
};
How to ignore this error #
You can use the identifier match.unhandled to ignore this error using a comment:
// @phpstan-ignore match.unhandled
codeThatProducesTheError();
You can also use only the identifier key to ignore all errors of the same type in your configuration file in the ignoreErrors parameter:
parameters:
ignoreErrors:
-
identifier: match.unhandled
Rules that report this error #
- PHPStan\Rules\Comparison\MatchExpressionRule [1]