Missing Switch Default
ID |
php.missing_switch_default |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Best Practice |
Language |
Php |
Tags |
best_practice, reliability |
Description
Reports a switch statement that has no default clause, in both the brace form and the
alternative switch (…): … endswitch; form. The PHP 8 match expression is not flagged
because it already throws when no arm matches.
Rationale
A switch without a default clause silently does nothing when the value matches none of the
case labels. That is fine until the matched expression gains a new possible value — a new
status code, a new state, a new request verb — at which point the previously exhaustive switch
quietly falls through and the bug is hard to trace. An explicit default documents the intended
catch-all behaviour and surfaces unexpected values immediately.
<?php
// FLAW — no default; an unknown verb falls through with no handling
switch ($verb) {
case 'GET': return 'read';
case 'POST': return 'create';
}
// OK — default clause handles every other value
switch ($verb) {
case 'GET': return 'read';
case 'POST': return 'create';
default: return 'unsupported';
}
Remediation
Add a default clause that handles the unmatched case — return a safe fallback, throw an
exception for truly unexpected input, or document the intentional no-op. Where every branch maps
a value to a result, a match expression is a stricter alternative that fails loudly on an
unhandled value.