Skip to content

Commit

Permalink
Fix for sortByDesc
Browse files Browse the repository at this point in the history
  • Loading branch information
TWithers committed Mar 8, 2024
1 parent d1602de commit 322f4c6
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
8 changes: 8 additions & 0 deletions src/Illuminate/Collections/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -1490,6 +1490,14 @@ protected function sortByMany(array $comparisons = [], int $options = SORT_REGUL
*/
public function sortByDesc($callback, $options = SORT_REGULAR)
{
if (is_array($callback) && ! is_callable($callback)) {
foreach ($callback as $index => $key) {
$comparison = Arr::wrap($key);
$comparison[1] = 'desc';
$callback[$index] = $comparison;
}
}

return $this->sortBy($callback, $options, true);
}

Expand Down
23 changes: 15 additions & 8 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2036,14 +2036,6 @@ public function testSortByString($collection)
$this->assertEquals([['name' => 'taylor'], ['name' => 'dayle']], array_values($data->all()));
}

#[DataProvider('collectionClassProvider')]
public function testSortByStringDesc($collection)
{
$data = new $collection([['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]);
$data = $data->sortByDesc(['id']);
$this->assertEquals([['id' => 2, 'name' => 'bar'], ['id' => 1, 'name' => 'foo']], array_values($data->all()));
}

/**
* @dataProvider collectionClassProvider
*/
Expand All @@ -2055,6 +2047,21 @@ public function testSortByCallableString($collection)
$this->assertEquals([['sort' => 1], ['sort' => 2]], array_values($data->all()));
}

#[DataProvider('collectionClassProvider')]
public function testSortByCallableStringDesc($collection)
{
$data = new $collection([['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]);
$data = $data->sortByDesc(['id']);
$this->assertEquals([['id' => 2, 'name' => 'bar'], ['id' => 1, 'name' => 'foo']], array_values($data->all()));

$data = new $collection([['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar'], ['id' => 2, 'name' => 'baz']]);
$data = $data->sortByDesc(['id']);
$this->assertEquals([['id' => 2, 'name' => 'bar'], ['id' => 2, 'name' => 'baz'], ['id' => 1, 'name' => 'foo']], array_values($data->all()));

$data = $data->sortByDesc(['id', 'name']);
$this->assertEquals([['id' => 2, 'name' => 'baz'], ['id' => 2, 'name' => 'bar'], ['id' => 1, 'name' => 'foo']], array_values($data->all()));
}

/**
* @dataProvider collectionClassProvider
*/
Expand Down

0 comments on commit 322f4c6

Please sign in to comment.