Completed
Push — master ( d78d08...71c71b )
by Milroy
20s
created

QueryBuilderAbstract::countExact()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Sarala\Query;
6
7
use Illuminate\Http\Request;
8
use Illuminate\Database\Eloquent\Builder;
9
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
10
11
abstract class QueryBuilderAbstract
12
{
13
    /** @var Request $request */
14
    protected $request;
15
16
    /** @var Builder $query */
17
    protected $query;
18
19
    /** @var Fields $fields */
20
    protected $fields;
21
22
    /** @var QueryParamBag $includes */
23
    protected $includes;
24
25
    /** @var QueryParamBag $filters */
26
    protected $filters;
27
28
    /** @var QueryHelper $queryHelper */
29
    private $queryHelper;
30
31
    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...
32
    {
33
        $this->request = $request;
34
        $this->fields = $this->request->fields();
35
        $this->includes = $this->request->includes();
36
        $this->filters = $this->request->filters();
37
        $this->query = $this->init();
38
        $this->queryHelper = new QueryHelper($this->query, $this->includes);
39
    }
40
41
    abstract protected function init(): Builder;
42
43
    protected function fields()
44
    {
45
        // ..
46
    }
47
48
    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...
49
    {
50
        // ..
51
    }
52
53
    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...
54
    {
55
        // ..
56
    }
57
58
    protected function sort(): array
59
    {
60
        return [];
61
    }
62
63
    public function exact($fields): QueryHelper
64
    {
65
        return $this->queryHelper->exact($fields);
66
    }
67
68
    public function countExact($fields): QueryHelper
69
    {
70
        return $this->queryHelper->countExact($fields);
71
    }
72
73
    public function alias($fields, $value): QueryHelper
74
    {
75
        return $this->queryHelper->alias($fields, $value);
76
    }
77
78
    public function countAlias($fields, $value): QueryHelper
79
    {
80
        return $this->queryHelper->countAlias($fields, $value);
81
    }
82
83
    public function fetch()
84
    {
85
        $this->fields();
86
87
        if ($this->request->filled('filter')) {
88
            $this->filter($this->filters);
89
        }
90
91
        if ($this->request->filled('include')) {
92
            $this->include($this->includes);
93
        }
94
95
        if ($this->request->filled('sort')) {
96
            $this->appendSortQuery();
97
        }
98
99
        if ($this->request->filled('page')) {
100
            return $this->appendParamsToPaginatedUrl();
101
        }
102
103
        return $this->query->get();
104
    }
105
106
    private function appendSortQuery(): void
107
    {
108
        $allowedSorts = $this->sort();
109
110
        $this->request->sorts()->each(function (SortField $field) use ($allowedSorts) {
111
            if (in_array($field->getField(), $allowedSorts)) {
112
                $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...
113
            }
114
        });
115
    }
116
117
    private function appendParamsToPaginatedUrl(): LengthAwarePaginator
118
    {
119
        $perPage = $this->request->input('page.size', 10);
120
        $page = $this->request->input('page.number', 1);
121
        $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 119 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 120 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...
122
123
        $paginator->appends($this->request->except('page'));
124
125
        foreach ($this->request->get('filter', []) as $key => $value) {
126
            if (is_null($value)) {
127
                $value = '';
128
            }
129
130
            $paginator->appends("filter[{$key}]", $value);
131
        }
132
133
        if (! is_null($this->request->input('page.size'))) {
134
            $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...
135
        }
136
137
        return $paginator;
138
    }
139
140
    public function fetchFirst()
141
    {
142
        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...
143
    }
144
}
145