Skip to content

Commit

Permalink
Rename order to direction, minimal refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
Kyslik committed Sep 4, 2018
1 parent 2396228 commit db597b8
Show file tree
Hide file tree
Showing 6 changed files with 108 additions and 122 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ There is a blade extension for you to use **@sortablelink()**
@sortablelink('column', 'Title', ['parameter' => 'smile'], ['rel' => 'nofollow'])
```

**Column** (1st) parameter is `order by`, **Title** (2nd) parameter is displayed inside anchor tags, `array()` parameter (3rd) is default (GET) query strings parameter and `array()` parameter (4th) is for additional anchor-tag attributes.
**Column** (1st) parameter is column in database, **Title** (2nd) parameter is displayed inside anchor tags, `array()` parameter (3rd) is default (GET) query strings parameter and `array()` parameter (4th) is for additional anchor-tag attributes.

You can omit 2nd, 3rd and 4th parameter.

Expand Down Expand Up @@ -170,10 +170,10 @@ Change the suffix class in the [config file](https://github.com/Kyslik/column-so

```php
/* this is FA 5 compatible.
suffix class that is appended when ascending order is applied */
suffix class that is appended when ascending direction is applied */
'asc_suffix' => '-up',

/* suffix class that is appended when descending order is applied */
/* suffix class that is appended when descending direction is applied */
'desc_suffix' => '-down',
```

Expand Down
3 changes: 1 addition & 2 deletions src/ColumnSortable/ColumnSortableServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
namespace Kyslik\ColumnSortable;

use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\ServiceProvider;

/**
Expand Down Expand Up @@ -38,7 +37,7 @@ public function boot()
return "<?php echo \Kyslik\ColumnSortable\SortableLink::render(array ({$expression}));?>";
});

Request::macro('allFilled', function (array $keys) {
request()->macro('allFilled', function (array $keys) {
foreach ($keys as $key) {
if ( ! $this->filled($key)) {
return false;
Expand Down
67 changes: 31 additions & 36 deletions src/ColumnSortable/Sortable.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
use BadMethodCallException;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Schema;
use Kyslik\ColumnSortable\Exceptions\ColumnSortableException;

Expand All @@ -18,25 +16,25 @@ trait Sortable

/**
* @param \Illuminate\Database\Query\Builder $query
* @param array|null $defaultSortParameters
* @param array|null $defaultParameters
*
* @return \Illuminate\Database\Query\Builder
* @throws \Kyslik\ColumnSortable\Exceptions\ColumnSortableException
*/
public function scopeSortable($query, $defaultSortParameters = null)
public function scopeSortable($query, $defaultParameters = null)
{
if (Request::allFilled(['sort', 'order'])) {
return $this->queryOrderBuilder($query, Request::only(['sort', 'order']));
if (request()->allFilled(['sort', 'direction'])) { // allFilled() is macro
return $this->queryOrderBuilder($query, request()->only(['sort', 'direction']));
}

if (is_null($defaultSortParameters)) {
$defaultSortParameters = $this->getDefaultSortable();
if (is_null($defaultParameters)) {
$defaultParameters = $this->getDefaultSortable();
}

if ( ! is_null($defaultSortParameters)) {
$defaultSortArray = $this->formatToSortParameters($defaultSortParameters);
if (Config::get('columnsortable.allow_request_modification', true) && ! empty($defaultSortArray)) {
Request::merge($defaultSortArray);
if ( ! is_null($defaultParameters)) {
$defaultSortArray = $this->formatToParameters($defaultParameters);
if (config('columnsortable.allow_request_modification', true) && ! empty($defaultSortArray)) {
request()->merge($defaultSortArray);
}

return $this->queryOrderBuilder($query, $defaultSortArray);
Expand All @@ -53,10 +51,10 @@ public function scopeSortable($query, $defaultSortParameters = null)
*/
private function getDefaultSortable()
{
if (Config::get('columnsortable.default_first_column', false)) {
if (config('columnsortable.default_first_column', false)) {
$sortBy = array_first($this->sortable);
if ( ! is_null($sortBy)) {
return [$sortBy => Config::get('columnsortable.default_direction', 'asc')];
return [$sortBy => config('columnsortable.default_direction', 'asc')];
}
}

Expand All @@ -76,7 +74,7 @@ private function queryOrderBuilder($query, array $sortParameters)
{
$model = $this;

list($column, $direction) = $this->parseSortParameters($sortParameters);
list($column, $direction) = $this->parseParameters($sortParameters);

if (is_null($column)) {
return $query;
Expand Down Expand Up @@ -115,20 +113,20 @@ private function queryOrderBuilder($query, array $sortParameters)


/**
* @param array $sortParameters
* @param array $parameters
*
* @return array
*/
private function parseSortParameters(array $sortParameters)
private function parseParameters(array $parameters)
{
$column = array_get($sortParameters, 'sort');
$column = array_get($parameters, 'sort');
if (empty($column)) {
return [null, null];
}

$direction = array_get($sortParameters, 'order', []);
$direction = array_get($parameters, 'direction', []);
if ( ! in_array(strtolower($direction), ['asc', 'desc'])) {
$direction = Config::get('columnsortable.default_direction', 'asc');
$direction = config('columnsortable.default_direction', 'asc');
}

return [$column, $direction];
Expand Down Expand Up @@ -157,16 +155,14 @@ private function queryJoinBuilder($query, $relation)
if ($relation instanceof HasOne) {
$relatedPrimaryKey = $relation->getQualifiedForeignKeyName();
$parentPrimaryKey = $relation->getQualifiedParentKeyName();

return $this->formJoin($query, $parentTable, $relatedTable, $parentPrimaryKey, $relatedPrimaryKey);
} elseif ($relation instanceof BelongsTo) {
$relatedPrimaryKey = $relation->getQualifiedOwnerKeyName();
$parentPrimaryKey = $relation->getQualifiedForeignKey();

return $this->formJoin($query, $parentTable, $relatedTable, $parentPrimaryKey, $relatedPrimaryKey);
} else {
throw new \Exception();
}

return $this->formJoin($query, $parentTable, $relatedTable, $parentPrimaryKey, $relatedPrimaryKey);
}


Expand All @@ -184,25 +180,25 @@ private function columnExists($model, $column)


/**
* @param array|string $sort
* @param array|string $array
*
* @return array
*/
private function formatToSortParameters($sort)
private function formatToParameters($array)
{
if (empty($sort)) {
if (empty($array)) {
return [];
}

$configDefaultOrder = Config::get('columnsortable.default_direction', 'asc');
$defaultDirection = config('columnsortable.default_direction', 'asc');

if (is_string($sort)) {
return ['sort' => $sort, 'order' => $configDefaultOrder];
if (is_string($array)) {
return ['sort' => $array, 'direction' => $defaultDirection];
}

return (key($sort) === 0) ? ['sort' => $sort[0], 'order' => $configDefaultOrder] : [
'sort' => key($sort),
'order' => reset($sort),
return (key($array) === 0) ? ['sort' => $array[0], 'direction' => $defaultDirection] : [
'sort' => key($array),
'direction' => reset($array),
];
}

Expand All @@ -218,9 +214,8 @@ private function formatToSortParameters($sort)
*/
private function formJoin($query, $parentTable, $relatedTable, $parentPrimaryKey, $relatedPrimaryKey)
{
$joinType = Config::get('columnsortable.join_type', 'leftJoin');
$joinType = config('columnsortable.join_type', 'leftJoin');

return $query->select($parentTable.'.*')
->{$joinType}($relatedTable, $parentPrimaryKey, '=', $relatedPrimaryKey);
return $query->select($parentTable.'.*')->{$joinType}($relatedTable, $parentPrimaryKey, '=', $relatedPrimaryKey);
}
}
58 changes: 27 additions & 31 deletions src/ColumnSortable/SortableLink.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

namespace Kyslik\ColumnSortable;

use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Request;
use Kyslik\ColumnSortable\Exceptions\ColumnSortableException;

/**
Expand All @@ -21,13 +19,12 @@ class SortableLink
*/
public static function render(array $parameters)
{
list($sortColumn, $sortParameter, $title, $queryParameters, $anchorAttributes) =
self::parseParameters($parameters);
list($sortColumn, $sortParameter, $title, $queryParameters, $anchorAttributes) = self::parseParameters($parameters);

$title = self::applyFormatting($title);

if ($mergeTitleAs = Config::get('columnsortable.inject_title_as', null)) {
Request::merge([$mergeTitleAs => $title]);
if ($mergeTitleAs = config('columnsortable.inject_title_as', null)) {
request()->merge([$mergeTitleAs => $title]);
}

list($icon, $direction) = self::determineDirection($sortColumn, $sortParameter);
Expand All @@ -40,7 +37,7 @@ public static function render(array $parameters)

$queryString = self::buildQueryString($queryParameters, $sortParameter, $direction);

return '<a'.$anchorClass.' href="'.url(Request::path().'?'.$queryString).'"'.$anchorAttributesString.'>'.htmlentities($title).$trailingTag;
return '<a'.$anchorClass.' href="'.url(request()->path().'?'.$queryString).'"'.$anchorAttributesString.'>'.htmlentities($title).$trailingTag;
}


Expand Down Expand Up @@ -76,7 +73,7 @@ public static function parseParameters(array $parameters)
*/
public static function explodeSortParameter($parameter)
{
$separator = Config::get('columnsortable.uri_relation_column_separator', '.');
$separator = config('columnsortable.uri_relation_column_separator', '.');

if (str_contains($parameter, $separator)) {
$oneToOneSort = explode($separator, $parameter);
Expand All @@ -98,7 +95,7 @@ public static function explodeSortParameter($parameter)
*/
private static function applyFormatting($title)
{
$formatting_function = Config::get('columnsortable.formatting_function', null);
$formatting_function = config('columnsortable.formatting_function', null);
if ( ! is_null($formatting_function) && function_exists($formatting_function)) {
$title = call_user_func($formatting_function, $title);
}
Expand All @@ -117,15 +114,15 @@ private static function determineDirection($sortColumn, $sortParameter)
{
$icon = self::selectIcon($sortColumn);

if (Request::get('sort') == $sortParameter && in_array(Request::get('order'), ['asc', 'desc'])) {
$icon .= (Request::get('order') === 'asc' ? Config::get('columnsortable.asc_suffix', '-asc') :
Config::get('columnsortable.desc_suffix', '-desc'));
$direction = Request::get('order') === 'desc' ? 'asc' : 'desc';
if (request()->get('sort') == $sortParameter && in_array(request()->get('direction'), ['asc', 'desc'])) {
$icon .= (request()->get('direction') === 'asc' ? config('columnsortable.asc_suffix', '-asc') :
config('columnsortable.desc_suffix', '-desc'));
$direction = request()->get('direction') === 'desc' ? 'asc' : 'desc';

return [$icon, $direction];
} else {
$icon = Config::get('columnsortable.sortable_icon');
$direction = Config::get('columnsortable.default_direction_unsorted', 'asc');
$icon = config('columnsortable.sortable_icon');
$direction = config('columnsortable.default_direction_unsorted', 'asc');

return [$icon, $direction];
}
Expand All @@ -139,9 +136,9 @@ private static function determineDirection($sortColumn, $sortParameter)
*/
private static function selectIcon($sortColumn)
{
$icon = Config::get('columnsortable.default_icon_set');
$icon = config('columnsortable.default_icon_set');

foreach (Config::get('columnsortable.columns', []) as $value) {
foreach (config('columnsortable.columns', []) as $value) {
if (in_array($sortColumn, $value['rows'])) {
$icon = $value['class'];
}
Expand All @@ -158,13 +155,13 @@ private static function selectIcon($sortColumn)
*/
private static function formTrailingTag($icon)
{
if ( ! Config::get('columnsortable.enable_icons', true)) {
if ( ! config('columnsortable.enable_icons', true)) {
return '</a>';
}

$iconAndTextSeparator = Config::get('columnsortable.icon_text_separator', '');
$iconAndTextSeparator = config('columnsortable.icon_text_separator', '');

$clickableIcon = Config::get('columnsortable.clickable_icon', false);
$clickableIcon = config('columnsortable.clickable_icon', false);
$trailingTag = $iconAndTextSeparator.'<i class="'.$icon.'"></i>'.'</a>';

if ($clickableIcon === false) {
Expand All @@ -190,21 +187,20 @@ private static function getAnchorClass($sortColumn, &$anchorAttributes = [])
{
$class = [];

$anchorClass = Config::get('columnsortable.anchor_class', null);
$anchorClass = config('columnsortable.anchor_class', null);
if ($anchorClass !== null) {
$class[] = $anchorClass;
}

$activeClass = Config::get('columnsortable.active_anchor_class', null);
$activeClass = config('columnsortable.active_anchor_class', null);
if ($activeClass !== null && self::shouldShowActive($sortColumn)) {
$class[] = $activeClass;
}

$orderClassPrefix = Config::get('columnsortable.order_anchor_class_prefix', null);
if ($orderClassPrefix !== null && self::shouldShowActive($sortColumn)) {
$class[] =
$orderClassPrefix.(Request::get('order') === 'asc' ? Config::get('columnsortable.asc_suffix', '-asc') :
Config::get('columnsortable.desc_suffix', '-desc'));
$directionClassPrefix = config('columnsortable.direction_anchor_class_prefix', null);
if ($directionClassPrefix !== null && self::shouldShowActive($sortColumn)) {
$class[] = $directionClassPrefix.(request()->get('direction') === 'asc' ? config('columnsortable.asc_suffix', '-asc') :
config('columnsortable.desc_suffix', '-desc'));
}

if (isset($anchorAttributes['class'])) {
Expand All @@ -223,7 +219,7 @@ private static function getAnchorClass($sortColumn, &$anchorAttributes = [])
*/
private static function shouldShowActive($sortColumn)
{
return Request::has('sort') && Request::get('sort') == $sortColumn;
return request()->has('sort') && request()->get('sort') == $sortColumn;
}


Expand All @@ -240,10 +236,10 @@ private static function buildQueryString($queryParameters, $sortParameter, $dire
return is_array($element) ? $element : strlen($element);
};

$persistParameters = array_filter(Request::except('sort', 'order', 'page'), $checkStrlenOrArray);
$persistParameters = array_filter(request()->except('sort', 'direction', 'page'), $checkStrlenOrArray);
$queryString = http_build_query(array_merge($queryParameters, $persistParameters, [
'sort' => $sortParameter,
'order' => $direction,
'sort' => $sortParameter,
'direction' => $direction,
]));

return $queryString;
Expand Down
Loading

0 comments on commit db597b8

Please sign in to comment.