Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New sniff: implement short ternary in select ternaries #12

Open
jrfnl opened this issue Jul 16, 2018 · 0 comments
Open

New sniff: implement short ternary in select ternaries #12

jrfnl opened this issue Jul 16, 2018 · 0 comments

Comments

@jrfnl
Copy link
Member

jrfnl commented Jul 16, 2018

Sniff basics -
Fixable for PHP: 5.3+
Sniff type: Modernize
Fixer type: Risky

Short description

PHP 5.3 introduced shorthand ternaries where the middle part can be left out.

Related PHPCompatibility sniff(s):

  • TernaryOperators

PHP manual references:

Example code:

Detect the following code pattern(s):

$a = $start ? $start : 0;

$can_drink = ( $age >= 21 ) 
  ? true 
  : false ;

$job_title = array_search( "Some Name", $emp )
  ? array_search( "Some Name", $emp )
  : "n/a" ;

// Don't fix:
$a = ( $start > 0 ) ? $start : 0;

And fix these to:

$a = $start ?: 0;

$can_drink = ( $age >= 21 ) 
  ?: false ;

$job_title = array_search( "Some Name", $emp )
  ?: "n/a" ;

Notes for implementation of the sniff:

  • Basically the sniff would need to verify that the part between the ? and the : is the same as the condition or true where the condition can only evaluate to a boolean.
  • Beware of nested ternaries.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant