Passed
Push — feature/optimize ( 219eef...0e0305 )
by Fu
03:34
created

ParserOrderByTrait   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 22
dl 0
loc 29
rs 10
c 0
b 0
f 0
wmc 6

1 Method

Rating   Name   Duplication   Size   Complexity  
B parserOrderBy() 0 27 6
1
<?php
2
3
4
namespace Modules\Core\Traits\Criteria;
5
6
7
use Illuminate\Support\Str;
8
9
/**
10
 * Trait ParserOrderByTrait
11
 *
12
 * @property \Illuminate\Http\Request $request
13
 * @property \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|\Illuminate\Database\Query\Builder $model
14
 * @package Modules\Core\Traits\Criteria
15
 */
16
trait ParserOrderByTrait
17
{
18
    protected function parserOrderBy()
19
    {
20
        $this->orderBy = $this->request->get(config('repository.criteria.params.orderBy', 'orderBy'), null);
0 ignored issues
show
Bug Best Practice introduced by
The property orderBy does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
21
        $this->sortedBy = $this->request->get(config('repository.criteria.params.sortedBy', 'sortedBy'), 'asc');
0 ignored issues
show
Bug Best Practice introduced by
The property sortedBy does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
22
        $this->sortedBy = !empty($this->sortedBy) ? $this->sortedBy : 'asc';
23
24
        if (isset($this->orderBy) && !empty($this->orderBy)) {
25
            $split = explode('|', $this->orderBy);
26
            if (count($split) > 1) {
27
                $table = $this->model->getModel()->getTable();
28
                $sortTable = $split[0];
29
                $sortColumn = $split[1];
30
31
                $split = explode(':', $sortTable);
32
                if (count($split) > 1) {
33
                    $sortTable = $split[0];
34
                    $keyName = $table.'.'.$split[1];
35
                } else {
36
                    $prefix = Str::singular($sortTable);
37
                    $keyName = $table.'.'.$prefix.'_id';
38
                }
39
40
                $this->model = $this->model->leftJoin($sortTable, $keyName, '=', $sortTable.'.id')
41
                                           ->orderBy($sortColumn, $this->sortedBy)
42
                                           ->addSelect($table.'.*');
43
            } else {
44
                $this->model = $this->model->orderBy($this->orderBy, $this->sortedBy);
45
            }
46
        }
47
    }
48
}