I have a method that utilizes switch - case blocks similar to the below chunk of code:
switch ($totalMonthsFromImmigration) {
case $totalMonthsFromImmigration <= 18:
$this->clauses->put('immigrant_1', $this->clauses->get('immigrant'));
$this->clauses->put('immigrant_2', null);
$this->clauses->put('immigrant_3', null);
break;
case $totalMonthsFromImmigration <= 30:
$this->clauses->put('immigrant_1', null);
$this->clauses->put('immigrant_2', $this->clauses->get('immigrant'));
$this->clauses->put('immigrant_3', null);
break;
case $totalMonthsFromImmigration <= 42:
$this->clauses->put('immigrant_1', null);
$this->clauses->put('immigrant_2', null);
$this->clauses->put('immigrant_3', $this->clauses->get('immigrant'));
break;
}
As it can be seen from the above example the cases make a similar things, and there's a little difference.
Is there a more elegant way to handle this situation? I don't really like the duplication of the code.
try to set default value then add value based on condition
$this->clauses->put('immigrant_1', null);
$this->clauses->put('immigrant_2', null);
$this->clauses->put('immigrant_3', null);
switch ($totalMonthsFromImmigration) {
case $totalMonthsFromImmigration <= 18:
$this->clauses->put('immigrant_1', $this->clauses->get('immigrant'));
break;
case $totalMonthsFromImmigration <= 30:
$this->clauses->put('immigrant_2', $this->clauses->get('immigrant'));
break;
case $totalMonthsFromImmigration <= 42:
$this->clauses->put('immigrant_3', $this->clauses->get('immigrant'));
break;
}