Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.6] Add sortKeys and sortKeysDesc methods to Collection. #23286

Merged
merged 1 commit into from
Feb 26, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -1475,6 +1475,33 @@ public function sortByDesc($callback, $options = SORT_REGULAR)
return $this->sortBy($callback, $options, true);
}

/**
* Sort the collection keys.
*
* @param int $options
* @param bool $descending
* @return static
*/
public function sortKeys($options = SORT_REGULAR, $descending = false)
{
$items = $this->items;

$descending ? krsort($items, $options) : ksort($items, $options);

return new static($items);
}

/**
* Sort the collection keys in descending order.
*
* @param int $options
* @return static
*/
public function sortKeysDesc($options = SORT_REGULAR)
{
return $this->sortKeys($options, true);
}

/**
* Splice a portion of the underlying collection array.
*
Expand Down
14 changes: 14 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -943,6 +943,20 @@ public function testSortByAlwaysReturnsAssoc()
$this->assertEquals([1 => 'dayle', 0 => 'taylor'], $data->all());
}

public function testSortKeys()
{
$data = new Collection(['b' => 'dayle', 'a' => 'taylor']);

$this->assertEquals(['a' => 'taylor', 'b' => 'dayle'], $data->sortKeys()->all());
}

public function testSortKeysDesc()
{
$data = new Collection(['a' => 'taylor', 'b' => 'dayle']);

$this->assertEquals(['b' => 'dayle', 'a' => 'taylor'], $data->sortKeys()->all());
}

public function testReverse()
{
$data = new Collection(['zaeed', 'alan']);
Expand Down