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 null coalescing operator in select ternaries #13

Open jrfnl opened 6 years ago

jrfnl commented 6 years ago
Sniff basics -
Fixable for PHP: 7.0+
Sniff type: Modernize
Fixer type: Safe/Risky

Short description

PHP 7.0 introduced the null coalescing operator to allow for abbreviating typical isset($x) ? $x : $y ternaries.

Related PHPCompatibility sniff(s):

PHP manual references:

Example code:

Detect the following code pattern(s):

$action = isset($_POST['action']) ? $_POST['action'] : 'default';

if (isset($_POST['action'])) {
    $action = $_POST['action'];
} else {
    $action = 'default';
}

$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

And fix these to:

$action = $_POST['action'] ?? 'default';

// The above is identical to this if/else statement
$action = $_POST['action'] ?? 'default';

$username = $_GET['user'] ?? 'nobody';

Notes for implementation of the sniff:

Prior art: