Skip to content

Commit

Permalink
Simplified sort by methods
Browse files Browse the repository at this point in the history
  • Loading branch information
kaidesu committed Jun 25, 2015
1 parent 1b6aa1a commit 8e36fa4
Showing 1 changed file with 19 additions and 26 deletions.
45 changes: 19 additions & 26 deletions src/Caffeinated/Menus/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ public static function formatGroupClass($new, $old)
*/

/**
* Fetches and returns all menu itemss.
* Fetches and returns all menu items.
*
* @return Collection
*/
Expand Down Expand Up @@ -423,37 +423,30 @@ public function filterRecursively($attribute, $value)
}

/**
* Sorts the menu based on user's callable.
* Sorts the menu based on key given in ascending order.
*
* @param string|callable $sortBy
* @param string $sortType
* @param string $key
* @return \Caffeinated\Menus\Builder
*/
public function sortBy($sortBy, $sortType = 'asc')
public function sortBy($key)
{
if (is_callable($sortBy)) {
$result = call_user_func($sortBy, $this->items->toArray());

if (! is_array($result)) {
$result = array($result);
}

$this->items = new Collection($result);
}

$this->items->sort(function ($itemA, $itemB) use ($sortBy, $sortType) {
$itemA = $itemA->$sortBy;
$itemB = $itemB->$sortBy;

if ($itemA == $itemB) {
return 0;
}
$this->items = $this->items->sortBy(function($item) use ($key) {
return $item->$key;
});

if ($sortType == 'asc') {
return $itemA > $itemB ? 1 : -1;
}
return $this;
}

return $itemA < $itemB ? 1 : -1;
/**
* Sorts the menu based on key given in descending order.
*
* @param string $key
* @return \Caffeinated\Menus\Builder
*/
public function sortByDesc($key)
{
$this->items = $this->items->sortByDesc(function($item) use ($key) {
return $item->$key;
});

return $this;
Expand Down

0 comments on commit 8e36fa4

Please sign in to comment.