Passed
Push — feature/optimize ( cf938e...7e8046 )
by Fu
03:43
created

ParseOrderByTrait::parseOrderBy()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 9
nc 6
nop 0
dl 0
loc 14
rs 9.6111
c 0
b 0
f 0
1
<?php
2
3
4
namespace Modules\Core\Traits\Criteria;
5
6
7
use Illuminate\Support\Str;
8
9
trait ParseOrderByTrait
10
{
11
    /** @var \Illuminate\Http\Request $request */
12
    protected $request;
13
    /** @var \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|\Illuminate\Database\Query\Builder $model */
14
    protected $model;
15
    /** @var \Prettus\Repository\Contracts\RepositoryInterface $repository */
16
    protected $repository;
17
    protected $search;
18
    protected $searchData;
19
    protected $searchFields;
20
    protected $isFirstField;
21
    protected $modelForceAndWhere;
22
    protected $fieldsSearchable;
23
    protected $fields;
24
    protected $filter;
25
    protected $orderBy;
26
    protected $sortedBy;
27
    protected $with;
28
    protected $searchJoin;
29
    protected $acceptedConditions;
30
    protected $originalFields;
31
32
    protected function parseOrderBy()
33
    {
34
        $this->orderBy = $this->request->get(config('repository.criteria.params.orderBy', 'orderBy'), null);
35
        $this->sortedBy = $this->request->get(config('repository.criteria.params.sortedBy', 'sortedBy'), 'asc');
36
        $this->sortedBy = !empty($this->sortedBy) ? $this->sortedBy : 'asc';
37
38
        if (isset($this->orderBy) && !empty($this->orderBy)) {
39
40
            $split = explode('|', $this->orderBy);
41
42
            if (count($split) > 1) {
43
                $this->multiOrderBy($split);
44
            } else {
45
                $this->orderBy();
46
            }
47
        }
48
    }
49
50
    protected function orderBy()
51
    {
52
        $this->model = $this->model->orderBy($this->orderBy, $this->sortedBy);
53
    }
54
55
    protected function multiOrderBy($split)
56
    {
57
        $table = $this->model->getModel()->getTable();
58
        $sortTable = $split[0];
59
        $sortColumn = $split[1];
60
61
        $split = explode(':', $sortTable);
62
63
        if (count($split) > 1) {
64
            $sortTable = $split[0];
65
            $keyName = $table.'.'.$split[1];
66
        } else {
67
            $prefix = Str::singular($sortTable);
68
            $keyName = $table.'.'.$prefix.'_id';
69
        }
70
71
        $this->model = $this->model->leftJoin($sortTable, $keyName, '=', $sortTable.'.id')
72
                                   ->orderBy($sortColumn, $this->sortedBy)
73
                                   ->addSelect($table.'.*');
74
    }
75
}