Available in PHPStan 2.1.7
Sometimes, you might want to ignore errors based on the Error, Node and Scope.
For example:
- Ignore
missingType.iterableValueon controller methods (actions): when the method is public and it has#[Route]attribute or the class has#[AsController]attribute. - Ignore
should return int but returns int|nullongetIdfor entities when the class has the#[Entity]attribute. - Ignore
never returns null so it can be removed from the return typewhen the method has#[GraphQL\Field]attribute. - Enforce
missingCheckedExceptionInThrowspartially, only for specific classes.
You can create an extension that implements IgnoreErrorExtension.
use PhpParser\Node;
use PHPStan\Analyser\Error;
use PHPStan\Analyser\IgnoreErrorExtension;
use PHPStan\Analyser\Scope;
// This extension will ignore "missingType.iterableValue" errors for public Action methods inside Controller classes.
final class ControllerActionReturnTypeIgnoreExtension implements IgnoreErrorExtension
{
public function shouldIgnore(Error $error, Node $node, Scope $scope): bool
{
if ($error->getIdentifier() !== 'missingType.iterableValue') {
return false;
}
if (!$scope->isInClass()) {
return false;
}
$classReflection = $scope->getClassReflection();
$methodReflection = $scope->getFunction();
if ($methodReflection === null) {
return false;
}
if (!str_ends_with($classReflection->getName(), 'Controller')) {
return false;
}
if (!str_ends_with($methodReflection->getName(), 'Action')) {
return false;
}
if (!$methodReflection->isPublic()) {
return false;
}
return true;
}
}
Prefer reading the context of the error from the Scope, like the example above does, over checking which node it was reported on. A rule can report an error on a different node in a new PHPStan version. For example, missing return types of methods with a body are now reported on MethodReturnStatementsNode instead of InClassMethodNode.
The implementation needs to be registered in your configuration file:
services:
-
class: MyApp\PHPStan\ControllerActionReturnTypeIgnoreExtension
tags:
- phpstan.ignoreErrorExtension
Alternatively, register it with the #[AutowiredService] attribute on the class. The phpstan.ignoreErrorExtension tag is added automatically based on the implemented interface.