PHPCSStandards / PHPCSExtra

A collection of code standards for use with PHP_CodeSniffer
GNU Lesser General Public License v3.0
90 stars 8 forks source link

:sparkles: New `Universal.CodeAnalysis.NoDoubleNegative` sniff #277

Closed jrfnl closed 10 months ago

jrfnl commented 11 months ago

... to detect double negatives (!!) and advise to use a boolean cast instead.

The sniff will correctly handle a situation where even more consecutive not operators are found.

In the case, the number of operators is uneven, it will auto-fix to a single not operator.

And when a double not operator is found before an expression involving instanceof, the error will still be thrown, but not auto-fix as the instanceof operator is nested right between the ! operator and a (bool) cast operator precedence wise, so auto-fixing without also adding parentheses would change the behaviour of the code.

Includes fixer. Includes unit tests. Includes documentation.

Ref: https://www.php.net/manual/en/language.operators.precedence.php

jrfnl commented 11 months ago

I wasn't able to test to confirm it, but this might be a case that isn't detecting the double !.

echo !@! $undefined_var;

Apparently you can silence the undefined variable warning in this way. Not sure why anyone would though. 🤷

Good point and no, the sniff would not flag that, but I'm not sure the sniff should catch that...