Error Identifier: ternary.alwaysTrue
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 doFoo(\stdClass $std): string
{
return $std ? 'yes' : 'no';
}
Why is it reported? #
The condition of the ternary operator always evaluates to true. This means the false branch ('no' in the example) is dead code and can never be reached.
In this example, $std is typed as \stdClass (a non-nullable object), which always evaluates to true in a boolean context. The ternary is therefore redundant.
How to fix it #
Remove the ternary and use the true branch value directly:
<?php declare(strict_types = 1);
function doFoo(\stdClass $std): string
{
- return $std ? 'yes' : 'no';
+ return 'yes';
}
If the condition should be nullable, adjust the type to reflect that:
<?php declare(strict_types = 1);
-function doFoo(\stdClass $std): string
+function doFoo(?\stdClass $std): string
{
return $std ? 'yes' : 'no';
}
How to ignore this error #
You can use the identifier ternary.alwaysTrue to ignore this error using a comment:
// @phpstan-ignore ternary.alwaysTrue
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: ternary.alwaysTrue
Rules that report this error #
- PHPStan\Rules\Comparison\TernaryOperatorConstantConditionRule [1]