QueryBuilderAbstract   A
last analyzed

Complexity

Total Complexity 25

Size/Duplication

Total Lines 144
Duplicated Lines 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
wmc 25
eloc 50
dl 0
loc 144
rs 10
c 1
b 1
f 0

14 Methods

Rating   Name   Duplication   Size   Complexity  
A appendParamsToPaginatedUrl() 0 21 4
A fields() 0 2 1
A __construct() 0 8 1
A exact() 0 3 1
A fetchFirst() 0 3 1
A filter() 0 2 1
A appendSortQuery() 0 7 2
A getInitialQuery() 0 10 4
A countExact() 0 3 1
A include() 0 2 1
A countAlias() 0 3 1
A alias() 0 3 1
A sort() 0 3 1
A fetch() 0 21 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Sarala\Query;
6
7
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
8
use Illuminate\Database\Eloquent\Builder;
9
use Illuminate\Database\Eloquent\Relations\Relation;
10
use Illuminate\Database\Query\Builder as QueryBuilder;
11
use Illuminate\Http\Request;
12
13
abstract class QueryBuilderAbstract
14
{
15
    /** @var Request */
16
    protected $request;
17
18
    /** @var Builder */
19
    protected $query;
20
21
    /** @var Fields */
22
    protected $fields;
23
24
    /** @var QueryParamBag */
25
    protected $includes;
26
27
    /** @var QueryParamBag */
28
    protected $filters;
29
30
    /** @var QueryHelper */
31
    private $queryHelper;
32
33
    public function __construct(Request $request)
34
    {
35
        $this->request = $request;
36
        $this->fields = $this->request->fields();
37
        $this->includes = $this->request->includes();
38
        $this->filters = $this->request->filters();
39
        $this->query = $this->getInitialQuery();
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->getInitialQuery() can also be of type Illuminate\Database\Eloquent\Relations\Relation or Illuminate\Database\Query\Builder. However, the property $query is declared as type Illuminate\Database\Eloquent\Builder. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
40
        $this->queryHelper = new QueryHelper($this->query, $this->includes);
41
    }
42
43
    abstract protected function init();
44
45
    protected function fields()
46
    {
47
        // ..
48
    }
49
50
    protected function filter(QueryParamBag $filters)
0 ignored issues
show
Unused Code introduced by
The parameter $filters is not used and could be removed. ( Ignorable by Annotation )

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

50
    protected function filter(/** @scrutinizer ignore-unused */ QueryParamBag $filters)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
51
    {
52
        // ..
53
    }
54
55
    protected function include(QueryParamBag $includes)
0 ignored issues
show
Unused Code introduced by
The parameter $includes is not used and could be removed. ( Ignorable by Annotation )

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

55
    protected function include(/** @scrutinizer ignore-unused */ QueryParamBag $includes)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
56
    {
57
        // ..
58
    }
59
60
    protected function sort(): array
61
    {
62
        return [];
63
    }
64
65
    public function exact($fields): QueryHelper
66
    {
67
        return $this->queryHelper->exact($fields);
68
    }
69
70
    public function countExact($fields): QueryHelper
71
    {
72
        return $this->queryHelper->countExact($fields);
73
    }
74
75
    public function alias($fields, $value = null): QueryHelper
76
    {
77
        return $this->queryHelper->alias($fields, $value);
78
    }
79
80
    public function countAlias($fields, $value = null): QueryHelper
81
    {
82
        return $this->queryHelper->countAlias($fields, $value);
83
    }
84
85
    public function fetch()
86
    {
87
        $this->fields();
88
89
        if ($this->request->filled('filter')) {
90
            $this->filter($this->filters);
91
        }
92
93
        if ($this->request->filled('include')) {
94
            $this->include($this->includes);
95
        }
96
97
        if ($this->request->filled('sort')) {
98
            $this->appendSortQuery();
99
        }
100
101
        if ($this->request->filled('page')) {
102
            return $this->appendParamsToPaginatedUrl();
103
        }
104
105
        return $this->query->get();
106
    }
107
108
    private function appendSortQuery(): void
109
    {
110
        $allowedSorts = $this->sort();
111
112
        $this->request->sorts()->each(function (SortField $field) use ($allowedSorts) {
113
            if (in_array($field->getField(), $allowedSorts)) {
114
                $this->query->orderBy($field->getField(), $field->getDirection());
115
            }
116
        });
117
    }
118
119
    private function appendParamsToPaginatedUrl(): LengthAwarePaginator
120
    {
121
        $perPage = $this->request->input('page.size', 10);
122
        $page = $this->request->input('page.number', 1);
123
        $paginator = $this->query->paginate($perPage, ['*'], 'page[number]', $page);
124
125
        $paginator->appends($this->request->except('page'));
126
127
        foreach ($this->request->get('filter', []) as $key => $value) {
128
            if (is_null($value)) {
129
                $value = '';
130
            }
131
132
            $paginator->appends("filter[{$key}]", $value);
133
        }
134
135
        if (! is_null($this->request->input('page.size'))) {
136
            $paginator->appends('page[size]', $this->request->input('page.size'));
137
        }
138
139
        return $paginator;
140
    }
141
142
    public function fetchFirst()
143
    {
144
        return $this->fetch()->first();
145
    }
146
147
    private function getInitialQuery()
148
    {
149
        $query = $this->init();
150
151
        if ($query instanceof Builder || $query instanceof QueryBuilder || $query instanceof Relation) {
152
            return $query;
153
        }
154
155
        throw new \Exception(
156
            'Expected init() method to return '.Builder::class.', '.QueryBuilder::class.' or a '.Relation::class.'. '.gettype($query).' returned.'
157
        );
158
    }
159
}
160