Completed
Push — master ( f02be9...1008e7 )
by Milroy
01:35
created

QueryBuilderAbstract::orderBy()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
cc 1
nc 1
nop 0
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 alias(string $name, $value): QueryHelper
69
    {
70
        return $this->queryHelper->alias($name, $value);
71
    }
72
73
    public function fetch()
74
    {
75
        $this->fields();
76
77
        if ($this->request->filled('filter')) {
78
            $this->filter($this->filters);
79
        }
80
81
        if ($this->request->filled('include')) {
82
            $this->include($this->includes);
83
        }
84
85
        if ($this->request->filled('sort')) {
86
            $this->appendSortQuery();
87
        }
88
89
        if ($this->request->filled('page')) {
90
            return $this->appendParamsToPaginatedUrl();
91
        }
92
93
        return $this->query->get();
94
    }
95
96
    private function appendSortQuery(): void
97
    {
98
        $allowedSorts = $this->sort();
99
100
        $this->request->sorts()->each(function (SortField $field) use ($allowedSorts) {
101
            if (in_array($field->getField(), $allowedSorts)) {
102
                $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...
103
            }
104
        });
105
    }
106
107
    private function appendParamsToPaginatedUrl(): LengthAwarePaginator
108
    {
109
        $perPage = $this->request->input('page.size', 10);
110
        $page = $this->request->input('page.number', 1);
111
        $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 109 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 110 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...
112
113
        $paginator->appends($this->request->except('page'));
114
115
        if (! is_null($this->request->input('page.size'))) {
116
            $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...
117
        }
118
119
        return $paginator;
120
    }
121
122
    public function fetchFirst()
123
    {
124
        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...
125
    }
126
}
127