PHP is weak (or loose) typed , so you need to give $val appropriately and / or approve its type if necessary:
function test($val) { assert('is_string($val)', 'expecting string'); switch((string)$val) { case 'a': }
An alternative is to use a dictionary:
$opts = [ 'a' => 'first', 'b' => 'first', ... ]; foreach ($opts as $opt => $response) { if ($opt === $val) { return $response; } } return 'default';
Since you are talking about running tests, keep in mind that the above has probably an undesirable side effect of masking cyclic complexity, i.e. you really have solutions to count($opts) +1, but the main cyclomatic complexity sees only two.
A more inconvenient setup that retains complexity (i.e. you get the correct code coverage from tests) may be
private function testA($val) { return 'first'; } private function testB($val) { return $this->testA($val); // or 'first' again } ... public function test($val) { if (!is_class_method($this, $method = 'test' . $val)) { $method = 'testDefault'; } $this->$method($val); }
The aforementioned drawback does not allow you to have all the options in a single unity (i.e. a switch) and can be accepted only if you have values ββthat can be used in the function name, and the check is case-insensitive, But after several attempts, I I find this effective compromise.
LSerni
source share