PHPCompatibility / PHPModernizer

External PHPCS standard with auto-fixers to modernize legacy codebases
GNU Lesser General Public License v3.0
10 stars 0 forks source link

New sniff: implement short ternary in select ternaries #12

Open jrfnl opened 6 years ago

jrfnl commented 6 years ago
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):

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: