From 01bcf71e376c305a0845c9d181eaa8f80215b2af Mon Sep 17 00:00:00 2001 From: Johannes Meyer Date: Tue, 5 Nov 2024 08:47:46 +0100 Subject: [PATCH] ArrayDatasource: Restore order by key column Broke with 384d9535a990c23fef3abc73657cb15931c2eba5 --- .../Icinga/Data/DataArray/ArrayDatasource.php | 16 ++++++----- .../Data/DataArray/ArrayDatasourceTest.php | 27 +++++++++++++++++++ 2 files changed, 37 insertions(+), 6 deletions(-) diff --git a/library/Icinga/Data/DataArray/ArrayDatasource.php b/library/Icinga/Data/DataArray/ArrayDatasource.php index e30061634..b67d74c17 100644 --- a/library/Icinga/Data/DataArray/ArrayDatasource.php +++ b/library/Icinga/Data/DataArray/ArrayDatasource.php @@ -196,7 +196,16 @@ class ArrayDatasource implements Selectable $filter = $query->getFilter(); $offset = $query->hasOffset() ? $query->getOffset() : 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()) { uasort($data, [$query, 'compare']); @@ -206,11 +215,6 @@ class ArrayDatasource implements Selectable $result = []; $skipped = 0; 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)) { continue; } elseif ($skipped < $offset) { diff --git a/test/php/library/Icinga/Data/DataArray/ArrayDatasourceTest.php b/test/php/library/Icinga/Data/DataArray/ArrayDatasourceTest.php index a40ad30d1..4c1fca3a4 100644 --- a/test/php/library/Icinga/Data/DataArray/ArrayDatasourceTest.php +++ b/test/php/library/Icinga/Data/DataArray/ArrayDatasourceTest.php @@ -132,4 +132,31 @@ class ArrayDatasourceTest extends BaseTestCase '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' + ); + } }