php-validated-properties icon indicating copy to clipboard operation
php-validated-properties copied to clipboard

Improve boolean handling in PropertyValidator

Open szepeviktor opened this issue 3 years ago • 5 comments
trafficstars

Just that.

szepeviktor avatar Jul 07 '22 10:07 szepeviktor

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.

PrinsFrank avatar Jul 10 '22 20:07 PrinsFrank

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.

szepeviktor avatar Jul 10 '22 20:07 szepeviktor

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.

szepeviktor avatar Jul 10 '22 20:07 szepeviktor

But a negating operator will result in the code being executed

FYI :)

$ php8.0 -r '$foo = "Foo bar"; var_dump(! $foo);'
bool(false)

szepeviktor avatar Jul 10 '22 20:07 szepeviktor

Type juggling and type casting belong to the bad parts of PHP (or any other language).

szepeviktor avatar Jul 10 '22 20:07 szepeviktor