php-validated-properties
php-validated-properties copied to clipboard
Improve boolean handling in PropertyValidator
Just that.
Hi @szepeviktor, thanks for all the great PRs! I don't know if I agree with this one though, can you explain why this is an improvement? IMHO a strict check is always better than a boolean NOT operator, because when the value being negated is not a boolean but a string for example, type conversion happens. for example:
$foo = 'Foo bar';
If we now check if foo is false, this will be false:
if ($foo === false) { // Will not execute }
But a negating operator will result in the code being executed:
if (! $foo) { // Will execute! }
Ideally, we wont do boolean checks on strings, and this might be enforced by a static analysis tool like PHPStan, but currently in this project this is not yet the case. That's why I prefer to be defensive in this case.
when the value being negated is not a boolean but a string
Yes. You are right. If your software is a trash dump you have to prepare for the worst.
But php-validated-properties is strictly typed and uses PHPStan.
In this specific case instanceof and isValid always return a boolean.
AFAIK PHPStan on a higher level or phpstan-strict-rules package will warn you if you use a boolean operator - e.g ! - in front of a non-boolean value.
But a negating operator will result in the code being executed
FYI :)
$ php8.0 -r '$foo = "Foo bar"; var_dump(! $foo);'
bool(false)
Type juggling and type casting belong to the bad parts of PHP (or any other language).