NestedTernaryOperator
warning on by defaultGroup: Confusing constructs · PhpStorm name: NestedTernaryOperatorInspection
A ternary inside another ternary is hard to read and, without parentheses, its associativity is a classic PHP trap. Chains of short ternaries ($a ?: $b ?: $c) read naturally and are accepted.
Example
php
<?php
$size = $big ? 'L' : ($mid ? 'M' : 'S');
$mode = $ro ? ($admin ? 'view-all' : 'view') : 'edit';
$state = (($on ? 1 : 0)) ? 'up' : 'down';
$name = ($nick ?: $first) ?: 'anon';
$name = $nick ?: ($first ?: 'anon');
$name = $nick ?: $first ?: $last ?: 'anon';
$call = $ok ? strtoupper($v ? 'y' : 'n') : '';Reported:
- line 2: Avoid nesting ternary operators; use if/else or extract a variable.
- line 3: Avoid nesting ternary operators; use if/else or extract a variable.
- line 4: Avoid nesting ternary operators; use if/else or extract a variable.
- line 5: Avoid nesting ternary operators; use if/else or extract a variable.
- line 6: Avoid nesting ternary operators; use if/else or extract a variable.
Configure
In custos.json:
json
{
"rules": {
"NestedTernaryOperator": {
"enabled": false
}
}
}Suppress
Before the statement or declaration (or the first statement of the file), either of:
php
// @custos-ignore NestedTernaryOperator
/**
* @noinspection NestedTernaryOperatorInspection
*/