ParseOrderByTrait::orderBy()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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