public function sort(array $fields)
{
foreach (array_reverse($fields) as $key => $value) {
// Uses usort with a function that will access the $key and sort in
// the $value direction. It mimics how the mongodb does sorting
// internally.
usort($this->items, function ($a, $b) use($key, $value) {
$a = is_object($a) ? $a->{$key} ?? null : $a[$key] ?? null;
$b = is_object($b) ? $b->{$key} ?? null : $b[$key] ?? null;
if ($a < $b) {
return $value * -1;
}
return $value;
});
}
return $this;
}