Skip to content

Commit 0b7067a

Browse files
authored
Merge pull request #2478 from miken32/patch-1
Use simple numeric sorting when dealing with numeric values
2 parents fb12721 + 9920a19 commit 0b7067a

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

src/CollectionDataTable.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -294,7 +294,15 @@ protected function getSorter(array $criteria)
294294
$first = $a;
295295
$second = $b;
296296
}
297-
if ($this->config->isCaseInsensitive()) {
297+
if (is_numeric($first[$column] ?? null) && is_numeric($second[$column] ?? null)) {
298+
if ($first[$column] < $second[$column]) {
299+
$cmp = -1;
300+
} elseif ($first[$column] > $second[$column]) {
301+
$cmp = 1;
302+
} else {
303+
$cmp = 0;
304+
}
305+
} elseif ($this->config->isCaseInsensitive()) {
298306
$cmp = strnatcasecmp($first[$column] ?? null, $second[$column] ?? null);
299307
} else {
300308
$cmp = strnatcmp($first[$column] ?? null, $second[$column] ?? null);

tests/Integration/CollectionDataTableTest.php

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,48 @@ public function it_can_sort_case_insensitive_strings()
130130
], $response->getData(true));
131131
}
132132

133+
/** @test */
134+
public function it_can_sort_numeric_strings()
135+
{
136+
config()->set('app.debug', false);
137+
request()->merge([
138+
'columns' => [
139+
['data' => 'amount', 'name' => 'amount', 'searchable' => 'true', 'orderable' => 'true'],
140+
],
141+
'order' => [['column' => 0, 'dir' => 'asc']],
142+
'start' => 0,
143+
'length' => 10,
144+
'draw' => 1,
145+
]);
146+
147+
$collection = collect([
148+
['amount' => '12'],
149+
['amount' => '7'],
150+
['amount' => '-8'],
151+
['amount' => '0'],
152+
['amount' => '-3'],
153+
['amount' => '8'],
154+
]);
155+
156+
$dataTable = app('datatables')->collection($collection);
157+
/** @var JsonResponse $response */
158+
$response = $dataTable->toJson();
159+
160+
$this->assertEquals([
161+
'draw' => 1,
162+
'recordsTotal' => 6,
163+
'recordsFiltered' => 6,
164+
'data' => [
165+
['amount' => '-8'],
166+
['amount' => '-3'],
167+
['amount' => '0'],
168+
['amount' => '7'],
169+
['amount' => '8'],
170+
['amount' => '12'],
171+
],
172+
], $response->getData(true));
173+
}
174+
133175
/** @test */
134176
public function it_accepts_a_model_using_ioc_container_factory()
135177
{

0 commit comments

Comments
 (0)