Skip to content

Commit

Permalink
Add sortKeys and sortKeysDesc methods to Collection.
Browse files Browse the repository at this point in the history
  • Loading branch information
pmatseykanets committed Feb 24, 2018
1 parent ebbefd8 commit 41da426
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
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

0 comments on commit 41da426

Please sign in to comment.