diff --git a/src/engine/Api/V1/Processors/Sort.php b/src/engine/Api/V1/Processors/Sort.php index e57a273c..2bc1a08a 100644 --- a/src/engine/Api/V1/Processors/Sort.php +++ b/src/engine/Api/V1/Processors/Sort.php @@ -14,7 +14,60 @@ namespace EA\Engine\Api\V1\Processors; class Sort implements ProcessorsInterface { + /** + * Supports up to 3 fields. + * + * @param array &$response The response array to be processed. + */ public static function process(array &$response) { - + if (!isset($_GET['sort'])) { + return; + } + + $sort = explode(',', (string)$_GET['sort']); + + $sortDirection1 = substr($sort[0], 0, 1) === '-' ? SORT_DESC : SORT_ASC; + + if (isset($sort[1])) { + $sortDirection2 = substr($sort[1], 0, 1) === '-' ? SORT_DESC : SORT_ASC; + } else { + $sortDirection2 = null; + } + + if (isset($sort[2])) { + $sortDirection3 = substr($sort[2], 0, 1) === '-' ? SORT_DESC : SORT_ASC; + } else { + $sortDirection3 = null; + } + + foreach ($response as $index => $entry) { + $sortOrder1[$index] = $entry[substr($sort[0], 1)]; + + if ($sortDirection2) { + $sortOrder2[$index] = $entry[substr($sort[1], 1)]; + } + + if ($sortDirection3) { + $sortOrder3[$index] = $entry[substr($sort[2], 1)]; + } + } + + $arguments = [ + $response, + $sortDirection1, + $sortOrder1 + ]; + + if ($sortDirection2) { + $arguments[] = $sortDirection2; + $arguments[] = $sortOrder2; + } + + if ($sortDirection3) { + $arguments[] = $sortDirection3; + $arguments[] = $sortOrder3; + } + + call_user_func_array('array_multisort', $arguments); } }