Skip to content

Commit 4c58c82

Browse files
fix: fixed sorting by multiple fields
1 parent 98368a5 commit 4c58c82

File tree

2 files changed

+18
-21
lines changed

2 files changed

+18
-21
lines changed

pfSense-pkg-RESTAPI/files/usr/local/pkg/RESTAPI/Core/Endpoint.inc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1133,7 +1133,7 @@ class Endpoint {
11331133
reverse: $this->reverse,
11341134
sort_by: $this->sort_by,
11351135
sort_order: constant($this->sort_order),
1136-
sort_flags: constant($this->sort_flags),
1136+
sort_flags: $this->sort_flags ? constant($this->sort_flags) : $this->model->sort_flags,
11371137
);
11381138
}
11391139
# For GET requests on many Endpoints, obtain all objects from the assigned Model.

pfSense-pkg-RESTAPI/files/usr/local/pkg/RESTAPI/Core/ModelSet.inc

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -93,36 +93,33 @@ class ModelSet {
9393
int $flags = SORT_REGULAR,
9494
bool $retain_ids = false,
9595
): ModelSet {
96-
# Variables
97-
$model_objects = $this->model_objects;
96+
# Ensure fields is an array
9897
$fields = is_array($fields) ? $fields : [$fields];
99-
$sort_criteria = [];
100-
101-
# Loop through each Model object and add the field values to the sort criteria
102-
foreach ($this->model_objects as $model_object) {
103-
# Loop variables
104-
$sort_values = [];
10598

106-
# Loop through each field to sort by and extract it's value
107-
foreach ($fields as $field) {
108-
$sort_values[] = $field === 'id' ? $model_object->id : $model_object->$field->value;
109-
}
110-
111-
# Add the sort values to the sort criteria
112-
$sort_criteria[] = $sort_values;
99+
# Extract sorting values for each field
100+
$sort_criteria = [];
101+
foreach ($fields as $field) {
102+
$sort_criteria[] = array_map(
103+
fn($model) => $field === 'id' ? $model->id : $model->$field->value, $this->model_objects
104+
);
105+
$sort_criteria[] = $order;
106+
$sort_criteria[] = $flags;
113107
}
114108

115-
# Sort using array_multisort
116-
array_multisort($sort_criteria, $order, $flags, $model_objects);
109+
# Append the actual model objects array for sorting
110+
$sort_criteria[] = &$this->model_objects;
111+
112+
# Sort the array
113+
array_multisort(...$sort_criteria);
117114

118-
# Re-assign the model object IDs if they should not be retained
115+
# Re-assign model object IDs if they should not be retained
119116
if (!$retain_ids) {
120-
foreach ($model_objects as $id => $model_object) {
117+
foreach ($this->model_objects as $id => $model_object) {
121118
$model_object->id = $id;
122119
}
123120
}
124121

125-
return new ModelSet($model_objects);
122+
return new ModelSet($this->model_objects);
126123
}
127124

128125
/**

0 commit comments

Comments
 (0)