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);
class Foo
{
/** @phpstan-assert-if-true int $value */
public function returnsString(mixed $value): string
{
return is_int($value) ? 'yes' : 'no';
}
}
Why is it reported? #
The @phpstan-assert-if-true and @phpstan-assert-if-false PHPDoc tags describe what a returned true or false says about the asserted expression. They only make sense when the function, method, or get property hook returns bool.
If the declared type is something else, like string, void, mixed, or bool|null, the condition the tag depends on is not reliably true or false. A null return value, a string, or no return value at all cannot be used to narrow types, so the tag either does nothing or narrows types in branches where it should not.
The error message says which tag is affected and which type was found instead of bool, for example:
PHPDoc tag @phpstan-assert-if-true above method Foo::returnsString() requires return type bool, string given.
For functions and methods, this check is currently available in Bleeding Edge. For get property hooks, it is always enabled.
How to fix it #
Change the return type to bool:
/** @phpstan-assert-if-true int $value */
-public function returnsString(mixed $value): string
+public function isInt(mixed $value): bool
{
- return is_int($value) ? 'yes' : 'no';
+ return is_int($value);
}
The same applies to a get hook. The property type has to be bool:
-public ?bool $hasName {
+public bool $hasName {
/** @phpstan-assert-if-true !null $this->name */
get => $this->name !== null;
}
If the function always narrows the type when it finishes without throwing, use the unconditional @phpstan-assert tag instead:
-/** @phpstan-assert-if-true int $value */
-public function check(mixed $value): void
+/** @phpstan-assert int $value */
+public function check(mixed $value): void
{
if (!is_int($value)) {
throw new \InvalidArgumentException();
}
}
How to ignore this error #
You can use the identifier assert.nonBool to ignore this error using a comment:
// @phpstan-ignore assert.nonBool
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: assert.nonBool