Completed
Push — master ( 74fac5...45df74 )
by Milroy
02:54
created

QueryBuilderAbstract::getInitialQuery()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
cc 4
nc 2
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Sarala\Query;
6
7
use Illuminate\Database\Eloquent\Relations\Relation;
8
use Illuminate\Database\Query\Builder as QueryBuilder;
9
use Illuminate\Http\Request;
10
use Illuminate\Database\Eloquent\Builder;
11
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
12
13
abstract class QueryBuilderAbstract
14
{
15
    /** @var Request $request */
16
    protected $request;
17
18
    /** @var Builder $query */
19
    protected $query;
20
21
    /** @var Fields $fields */
22
    protected $fields;
23
24
    /** @var QueryParamBag $includes */
25
    protected $includes;
26
27
    /** @var QueryParamBag $filters */
28
    protected $filters;
29
30
    /** @var QueryHelper $queryHelper */
31
    private $queryHelper;
32
33
    public function __construct(Request $request)
0 ignored issues
show
Bug introduced by
You have injected the Request via parameter $request. This is generally not recommended as there might be multiple instances during a request cycle (f.e. when using sub-requests). Instead, it is recommended to inject the RequestStack and retrieve the current request each time you need it via getCurrentRequest().
Loading history...
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 object<Illuminate\Database\Query\Builder> or object<Illuminate\Databa...ent\Relations\Relation>. However, the property $query is declared as type object<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.

This check looks from 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.

This check looks from 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());
0 ignored issues
show
Bug introduced by
The method orderBy() does not exist on Illuminate\Database\Eloquent\Builder. Did you maybe mean enforceOrderBy()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
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);
0 ignored issues
show
Bug introduced by
It seems like $perPage defined by $this->request->input('page.size', 10) on line 121 can also be of type array or string; however, Illuminate\Database\Eloquent\Builder::paginate() does only seem to accept integer|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
Bug introduced by
It seems like $page defined by $this->request->input('page.number', 1) on line 122 can also be of type array or string; however, Illuminate\Database\Eloquent\Builder::paginate() does only seem to accept integer|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
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'));
0 ignored issues
show
Bug introduced by
It seems like $this->request->input('page.size') targeting Illuminate\Http\Concerns...ractsWithInput::input() can also be of type array; however, Illuminate\Contracts\Pag...on\Paginator::appends() does only seem to accept string|null, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
137
        }
138
139
        return $paginator;
140
    }
141
142
    public function fetchFirst()
143
    {
144
        return $this->fetch()->first();
0 ignored issues
show
Bug introduced by
The method first does only exist in Illuminate\Database\Eloquent\Collection, but not in Illuminate\Contracts\Pag...on\LengthAwarePaginator.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
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