codeclimate / codeclimate-phpcodesniffer

Code Climate Engine for PHP Code Sniffer
MIT License
28 stars 23 forks source link

Cognitive complexity calculation error #87

Open bkdotcom opened 2 years ago

bkdotcom commented 2 years ago

I apologize if this isn't the correct repo to report this

CodeClimate reports the Cognitive Complexity of the following function as 14 I believe the value should be 12

It seems that CodeClimate is incorrectly incrementing the continue statements

function testFunction($array)
{
    if (false) {
        return;
    }
    $file = '';
    $line = 0;
    if (false) {
        throw new \RuntimeException('false was true! ');
    }
    foreach ($array as $key => $val) {
        if (\is_int($key)) {
            continue;
        }
        if (\is_string($val)) {
            continue;
        }
        if (\is_array($val)) {
            foreach ($val as $val2) {
                // empty
            }
        }
    }
}

continue; should not increment

continue LABEL; should increment

bkdotcom commented 2 years ago

The cognitive complexity whitepaper is a bit vague/ambiguous

https://www.sonarsource.com/docs/CognitiveComplexity.pdf

Jumps to labels

goto adds a fundamental increment to Cognitive Complexity, as do break or continue to a label and other multi-level jumps such as the break or continue to a number found in some languages. But because an early return can often make code much clearer, no other jumps or early exits cause an increment.

B1. Increments

  • goto LABEL, break LABEL, continue LABEL, break NUMBER, continue NUMBER

Appendix C has a code examples containing a break; (break without a label)
No increment in assigned/given