Cyclomatic Complexity
ID |
php.cyclomatic_complexity |
Severity |
info |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Complexity |
Language |
Php |
Tags |
complexity |
Description
Reports functions, methods and closures whose cyclomatic complexity exceeds a configurable
threshold (default 30). Cyclomatic complexity counts the number of linearly-independent
paths through a routine; it grows with every branch — if/elseif, loops, switch cases,
catch clauses and the like. The value is computed from the routine’s control-flow graph.
Rationale
A high cyclomatic complexity means many independent execution paths, which makes a routine hard to read, hard to reason about and hard to cover with tests: the number of test cases needed to exercise every path grows with the metric. Routines that accumulate branch after branch tend to mix several responsibilities and become a magnet for defects when changed.
<?php
class Classifier
{
public function classify(int $n): string // FLAW — far too many branches
{
if ($n < 0) { return 'negative'; }
if ($n === 0) { return 'zero'; }
if ($n === 1) { return 'one'; }
if ($n === 2) { return 'two'; }
for ($i = 1; $i < $n; $i++) {
if ($i % 2 === 0) { continue; }
if ($i % 3 === 0) { continue; }
}
if ($n > 1000) { return 'big'; }
if ($n < -1000) { return 'small'; }
return 'normal';
}
public function trivial(int $a, int $b): int
{
return $a + $b; // OK — straight-line, complexity 1
}
}
Remediation
Break the routine into smaller, single-responsibility helpers. Replace long if/elseif
ladders or switch blocks with a lookup table or polymorphism, use guard clauses to flatten
nesting, and extract loop bodies into their own functions. Tune the maxCcn property to
match your team’s standard.