Skip to content

New sniff: implement short ternary in select ternaries #12

@jrfnl

Description

@jrfnl
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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions