AutoSort::scopeAutoSort()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 21
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 16
dl 0
loc 21
c 0
b 0
f 0
rs 9.7333
cc 3
nc 3
nop 3
1
<?php
2
3
namespace Turahe\Master\Traits;
4
5
use Illuminate\Database\Eloquent\Builder;
6
use Illuminate\Support\Str;
7
8
trait AutoSort
9
{
10
    public function scopeAutoSort(Builder $query, $sortByKey = 'sort', $sortDirectionKey = 'direction')
11
    {
12
        $direction = request()->get($sortDirectionKey, 'asc');
13
14
        if (request()->has($sortByKey)) {
15
            $column = request()->get($sortByKey);
16
            if (Str::contains($column, '.')) {
17
                $temp = explode('.', $column);
18
                $relation = $this->{$temp[0]}();
19
                $related = $relation->getRelated();
20
                $table = $related->getTable();
21
                $column = $temp[1];
22
23
                $foreignKey = $relation->getQualifiedForeignKeyName();
24
                $ownerKey = $relation->getQualifiedOwnerKeyName();
25
26
                $query->select($this->getTable().'.*');
0 ignored issues
show
Bug introduced by
It seems like getTable() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

26
                $query->select($this->/** @scrutinizer ignore-call */ getTable().'.*');
Loading history...
27
                $query->join($table, $foreignKey, '=', $ownerKey);
28
                $query->orderBy($table.'.'.$column, $direction);
29
            } else {
30
                $query->orderBy($column, $direction);
31
            }
32
        }
33
    }
34
}
35