Skip to content

Ternary Operator and Null Coalescing Operator are not counted in Generic.Metrics.CyclomaticComplexity #3469

@MarkBaker

Description

@MarkBaker

The Ternary and Null Coalescing Operator (and the Corresponding Null Coalescing Assignment Operator) are not taken into consideration when calculating complexity in the Generic.Metrics.CyclomaticComplexity sniff.

All three of these operators should increment the Cyclomatic Complexity score by 1, because there are two paths through the code each cases.

A ternary like

$result = ($condition) ? $value1 : $value2;

can be re-written as an if/else statement

if ($condition) {
    $result = $value1
} else {
    $result = $value2;
}

with two branches through the code, which should increment the CYC count by one.

Similarly, the Null Coalescing Operator

$result = $value1 ?? $value2;

can be written as

if ($value1 !== null) {
    $result = $value1
} else {
    $result = $value2;
}

while the Null Coalescing Assignment Operator

$value1 ??= $value1 ?? $value2;

can be written as

if ($value1 === null) {
    $value1 = $value2;
}

also two branches through the code, which should increment the CYC count by one in each case.

These cases can be resolved by adding the T_INLINE_THEN, T_COALESCE and T_COALESCE_EQUAL tokens to the list of tokens that increase CYC by one.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions