-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Labels
Description
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:
-
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
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 ortrue
where the condition can only evaluate to a boolean. - Beware of nested ternaries.