coding-standards icon indicating copy to clipboard operation
coding-standards copied to clipboard

#154 - Add new Ternary sniff

Open tfrommen opened this issue 5 years ago • 1 comments

This PR adds a new sniff, HM.PHP.Ternary that adds a warning for unnecessary ternary expression, as mentioned in #154:

  • $expr ? true : false;
  • $expr ? false : true.

See fixtures for (passing and failing) example code.

Output is as follows:

  3 | WARNING | Unnecessary ternary found: Instead of "$expr ? true : false", use "(bool) $expr"
  4 | WARNING | Unnecessary ternary found: Instead of "$expr ? false : true", use "! $expr"

Can anyone think of any edge-case usage that the sniff would either flag as false-positive, or that it would miss?

I'm not 100% sure I considered all tokens that would end the ternary, which currently are: semicolon, closing parenthesis, closing curly brace (function or any other scope), and also comma (which I just added in a subsequent commit). Anything else? Maybe @jrfnl? 🙂

tfrommen avatar Oct 28 '20 14:10 tfrommen

Instead of a custom sniff, we might want to use the UselessTernaryOperatorSniff one included in the Slevomat Coding Standards...? This one is also fixable, which is nice.

I think I will create a separate issue to discuss pulling in the Slevomat Coding Standards...

tfrommen avatar Feb 04 '21 11:02 tfrommen