I came across this solution, avoiding the switch statement alltogether:
$sort_functions = array(
'number' => function($a, $b){ return ( (int) $a->number > (int) $b->number ); },
'client' => function($a, $b){ return strcmp($a->client_contact_last_name, $b->client_contact_last_name); },
'name' => function($a, $b){ return strcmp($a->name, $b->name); },
'status' => function($a, $b){ return ( (int) $a->status > (int) $b->status ); },
'revenue' => function($a, $b){ return ( (float) $a->base_revenue > (float) $b->base_revenue ); },
'profit' => function($a, $b){ return ( (float) $a->profit > (float) $b->profit ); },
'margin' => function($a, $b){ return ( (float) $a->margin > (float) $b->margin ); },
);
if (isset($sort_functions[$sort])) {
usort($jobs_list, $sort_functions[$sort]);
}
Bonus: It is easily extensible should new fields appear. Negative: Still a lot of code duplication for three basic comparisons... But we will address it:
Extracting all basic functions into separate variables (an array would work here, too), and adding the field that should be compared to this function, you get an almost universal arsenal of comparison of object properties.
$intcompare = function($a, $b, $field){ return ( (int) $a->$field > (int) $b->$field ); };
$stringcompare = function($a, $b, $field){ return strcmp($a->$field, $b->$field); };
$floatcompare = function($a, $b, $field){ return ( (float) $a->$field > (float) $b->$field); };
Call these functions by passing them into the anonymous functions for each field.
$sort_functions = array(
'number' => function($a, $b) use ($intcompare) { return $intcompare($a, $b, 'number'); },
'client' => function($a, $b) use ($stringcompare) { return $stringcompare($a, $b, 'client_contact_last_name'); },
'name' => function($a, $b) use ($stringcompare) { return $stringcompare($a, $b, 'name'); },
'status' => function($a, $b) use ($intcompare) { return $intcompare($a, $b, 'status' ); },
'revenue' => function($a, $b) use ($floatcompare) { return $floatcompare($a, $b, 'base_revenue' ); },
'profit' => function($a, $b) use ($floatcompare) { return $floatcompare($a, $b, 'profit' ); },
'margin' => function($a, $b) use ($floatcompare) { return $floatcompare($a, $b, 'margin' ); },
);
if (isset($sort_functions[$sort])) {
usort($jobs_list, $sort_functions[$sort]);
}
Testing if it works:
$jobs_list = array(
(object) array('number' => 1),
(object) array('number' => 0),
);
$sort = 'number';
var_dump($jobs_list);
if (isset($sort_functions[$sort])) {
usort($jobs_list, $sort_functions[$sort]);
}
var_dump($jobs_list);
Result:
array(2) {
[0] =>
class stdClass#11 (1) {
public $number =>
int(1)
}
[1] =>
class stdClass#12 (1) {
public $number =>
int(0)
}
}
array(2) {
[0] =>
class stdClass#12 (1) {
public $number =>
int(0)
}
[1] =>
class stdClass#11 (1) {
public $number =>
int(1)
}
}