Skip to content

Commit

Permalink
Added the ability to use a callback for sorting
Browse files Browse the repository at this point in the history
Simply add a function to the model in question named like
“sortFieldName” where “FieldName” is the studly-case variation of the
name of the field targeted.
  • Loading branch information
gbrock committed Aug 6, 2015
1 parent 452034f commit 7902520
Showing 1 changed file with 27 additions and 5 deletions.
32 changes: 27 additions & 5 deletions src/Traits/Sortable.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,31 @@ public function scopeSorted($query, $field = false, $direction = false)
$direction = $this->getSortingDirection();
}

// If we tried to sort a Model which can't be sorted, fail loudly.
if(!isset($this->sortable) || !is_array($this->sortable))
if(
!isset($this->sortable) || // are sortables present?
!is_array($this->sortable) // are the sortables an array?
)
{
// If we tried to sort a Model which can't be sorted, fail loudly.
throw new ModelMissingSortableArrayException;
}

// The name of the custom function (which may or may not exist) which sorts this field
$sortFunctionName = 'sort' . studly_case($field);

// does $field appear as a VALUE in list of known sortables?
$isValueOfSortable = in_array($field, (array) $this->sortable);
// does $field appear as a KEY in list of known sortables?
$isKeyOfSortable = isset($this->sortable[$field]);
// is there a custom function for sorting this column?
$isCallableFunction = method_exists($this, $sortFunctionName);

// If the field requested isn't known to be sortable by our model, fail silently.
if(!in_array($field, (array) $this->sortable) && !isset($this->sortable[$field]))
if(
!$isValueOfSortable &&
!$isKeyOfSortable &&
!$isCallableFunction
)
{
return $query;
}
Expand All @@ -34,16 +51,21 @@ public function scopeSorted($query, $field = false, $direction = false)
$direction = config('gbrock-tables.default_direction');
}

if(isset($this->sortable[$field]))
if($isKeyOfSortable)
{
// Set via key
$sortField = $this->sortable[$field];
}
elseif(in_array($field, $this->sortable))
elseif($isValueOfSortable)
{
// Does the passed field contain a period character?
$sortField = strpos($field, '.') === FALSE ? $this->getTable() . '.' . $field : $field;
}
elseif($isCallableFunction)
{
// Call custom function and return immediately
return call_user_func([$this, $sortFunctionName], $query, $direction);
}

// At this point, all should be well, continue.
return $query
Expand Down

0 comments on commit 7902520

Please sign in to comment.