Error Identifier: function.alreadyNarrowedType
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);
function process(int $value): void
{
if (is_int($value)) {
echo $value;
}
}
Why is it reported? #
A type-checking function call will always evaluate to true because the type of the argument has already been narrowed to match the check. This means the condition is redundant – the type is already guaranteed by a previous check, a type declaration, or the control flow.
In the example above, $value is declared as int, so is_int($value) is always true.
How to fix it #
Remove the unnecessary type check when the type is already guaranteed by the parameter type:
<?php declare(strict_types = 1);
function process(int $value): void
{
- if (is_int($value)) {
- echo $value;
- }
+ echo $value;
}
If the function accepts a union type, the check may become meaningful:
<?php declare(strict_types = 1);
-function process(int $value): void
+function process(int|string $value): void
{
if (is_int($value)) {
echo $value;
}
}
How to ignore this error #
You can use the identifier function.alreadyNarrowedType to ignore this error using a comment:
// @phpstan-ignore function.alreadyNarrowedType
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: function.alreadyNarrowedType
Rules that report this error #
- PHPStan\Rules\Comparison\ImpossibleCheckTypeFunctionCallRule [1]