✨ New Universal.CodeAnalysis.NoDoubleNegative sniff#277
Conversation
... 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
5133267 to
8ec8a17
Compare
diedexx
left a comment
There was a problem hiding this comment.
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. 🤷
| // Collect all the operators only once. | ||
| $this->operatorsWithLowerPrecedence = Tokens::$assignmentTokens; | ||
| $this->operatorsWithLowerPrecedence += Tokens::$booleanOperators; | ||
| $this->operatorsWithLowerPrecedence += Tokens::$comparisonTokens; | ||
| $this->operatorsWithLowerPrecedence += Tokens::$operators; | ||
| $this->operatorsWithLowerPrecedence[\T_INLINE_THEN] = \T_INLINE_THEN; | ||
| $this->operatorsWithLowerPrecedence[\T_INLINE_ELSE] = \T_INLINE_ELSE; |
There was a problem hiding this comment.
Out of curiosity: why not use the constructor for this?
There was a problem hiding this comment.
It's rare for a sniff to have a constructor and the register() method is normally only called once anyway, so as good a place as any to do this in.
Good point and no, the sniff would not flag that, but I'm not sure the sniff should catch that... |
... 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 theinstanceofoperator 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