ArrayDatasource: Restore order by key column

Broke with 384d9535a9
This commit is contained in:
Johannes Meyer 2024-11-05 08:47:46 +01:00
parent eea50d7d6b
commit 01bcf71e37
2 changed files with 37 additions and 6 deletions

View File

@ -196,7 +196,16 @@ class ArrayDatasource implements Selectable
$filter = $query->getFilter(); $filter = $query->getFilter();
$offset = $query->hasOffset() ? $query->getOffset() : 0; $offset = $query->hasOffset() ? $query->getOffset() : 0;
$limit = $query->hasLimit() ? $query->getLimit() : 0; $limit = $query->hasLimit() ? $query->getLimit() : 0;
$data = $this->data;
$data = [];
foreach ($this->data as $key => $row) {
if ($this->keyColumn !== null && ! isset($row->{$this->keyColumn})) {
$row = clone $row; // Make sure that this won't affect the actual data
$row->{$this->keyColumn} = $key;
}
$data[$key] = $row;
}
if ($query->hasOrder()) { if ($query->hasOrder()) {
uasort($data, [$query, 'compare']); uasort($data, [$query, 'compare']);
@ -206,11 +215,6 @@ class ArrayDatasource implements Selectable
$result = []; $result = [];
$skipped = 0; $skipped = 0;
foreach ($data as $key => $row) { foreach ($data as $key => $row) {
if ($this->keyColumn !== null && !isset($row->{$this->keyColumn})) {
$row = clone $row; // Make sure that this won't affect the actual data
$row->{$this->keyColumn} = $key;
}
if (! $filter->matches($row)) { if (! $filter->matches($row)) {
continue; continue;
} elseif ($skipped < $offset) { } elseif ($skipped < $offset) {

View File

@ -132,4 +132,31 @@ class ArrayDatasourceTest extends BaseTestCase
'ArrayDatasource does not sort limited queries correctly' 'ArrayDatasource does not sort limited queries correctly'
); );
} }
public function testOrderByKeyColumnIsCorrect()
{
$result = (new ArrayDatasource([
'a' => (object) [
'foo' => 'bar',
'baz' => 'qux'
],
'b' => (object) [
'foo' => 'bar',
'baz' => 'qux'
],
'c' => (object) [
'foo' => 'bar',
'baz' => 'qux'
]
]))->setKeyColumn('name')
->select()
->order('name', 'desc')
->fetchAll();
$this->assertSame(
['c', 'b', 'a'],
array_keys($result),
'ArrayDatasource does not sort queries correctly by key column'
);
}
} }