Paginator::compileWhere()   A
last analyzed

Complexity

Conditions 5
Paths 1

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
nc 1
nop 2
dl 0
loc 15
ccs 10
cts 10
cp 1
crap 5
rs 9.4555
c 0
b 0
f 0
1
<?php
2
3
namespace mav3rick177\RapidPagination;
4
5
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
6
use Illuminate\Support\Traits\Macroable;
7
use mav3rick177\RapidPagination\Base\Concerns\HasProcessor;
8
use mav3rick177\RapidPagination\Base\Contracts\Cursor;
9
use mav3rick177\RapidPagination\Base\Paginator as BasePaginator;
10
use mav3rick177\RapidPagination\Base\Query;
11
use mav3rick177\RapidPagination\Base\Query\Select;
12
use mav3rick177\RapidPagination\Base\Query\SelectOrUnionAll;
13
use mav3rick177\RapidPagination\Base\Query\UnionAll;
14
15
/**
16
 * Class Paginator
17
 *
18
 * @see BasePaginator, HasProcessor
19
 */
20
class Paginator extends BasePaginator
21
{
22
    use Macroable, HasProcessor;
23
24
    /**
25
     * @param  \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Relations\Relation|\Illuminate\Database\Query\Builder $builder
26
     * @return static
27
     */
28 19
    public static function create($builder)
29
    {
30 19
        return new static($builder);
31
    }
32
33
    /**
34
     * Paginator constructor.
35
     *
36
     * @param \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Relations\Relation|\Illuminate\Database\Query\Builder $builder
37
     */
38 19
    public function __construct($builder)
39
    {
40 19
        $this->builder = $builder;
41 19
        $this->processor = new Processor();
42
    }
43
44
    /**
45
     * Build Illuminate Builder instance from Query config.
46
     *
47
     * @param  Query                                                                                                                     $query
48
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Relations\Relation|\Illuminate\Database\Query\Builder
49
     */
50 17
    public function transform(Query $query)
51
    {
52 17
        return $this->compileSelectOrUnionAll($query->selectOrUnionAll());
53
    }
54
55
    /**
56
     * Configure -> Transform.
57
     *
58
     * @param  Cursor|int[]|string[]                                                                                                     $cursor
59
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Relations\Relation|\Illuminate\Database\Query\Builder
60
     */
61 15
    public function build($cursor = [])
62
    {
63 15
        return $this->transform($this->configure($cursor));
64
    }
65
66
    /**
67
     * Execute query and paginate them.
68
     *
69
     * @param  Cursor|int[]|string[]  $cursor
70
     * @return mixed|PaginationResult
71
     */
72 2
    public function paginate($cursor = [])
73
    {
74 2
        $query = $this->configure($cursor);
75 2
        return $this->process($query, $this->transform($query)->get());
76
    }
77
78
    /**
79
     * @param  SelectOrUnionAll                                                                                                          $selectOrUnionAll
80
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Relations\Relation|\Illuminate\Database\Query\Builder
81
     */
82 17
    protected function compileSelectOrUnionAll(SelectOrUnionAll $selectOrUnionAll)
83
    {
84 17
        if ($selectOrUnionAll instanceof Select) {
85 7
            return $this->compileSelect($selectOrUnionAll);
86
        }
87 10
        if ($selectOrUnionAll instanceof UnionAll) {
88 10
            $supportQuery = $this->compileSelect($selectOrUnionAll->supportQuery());
89 10
            $mainQuery = $this->compileSelect($selectOrUnionAll->mainQuery());
90 10
            return $supportQuery->unionAll($this->addSelectForUnionAll($mainQuery));
0 ignored issues
show
Bug introduced by
It seems like $this->addSelectForUnionAll($mainQuery) targeting mav3rick177\RapidPaginat...:addSelectForUnionAll() can also be of type object<Illuminate\Database\Eloquent\Builder> or object<Illuminate\Databa...ent\Relations\Relation>; however, Illuminate\Database\Query\Builder::unionAll() does only seem to accept object<Illuminate\Databa...uilder>|object<Closure>, 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...
Bug introduced by
The method unionAll does only exist in Illuminate\Database\Query\Builder, but not in Illuminate\Database\Eloq...uent\Relations\Relation.

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...
91
        }
92
        // @codeCoverageIgnoreStart
93
        throw new \LogicException('Unreachable here');
94
        // @codeCoverageIgnoreEnd
95
    }
96
97
    /**
98
     * @param  Select                                                                                                                    $select
99
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Relations\Relation|\Illuminate\Database\Query\Builder
100
     */
101 17
    protected function compileSelect(Select $select)
102
    {
103 17
        $builder = clone $this->builder;
104
        $this
105 17
            ->compileWhere($builder, $select)
106 17
            ->compileOrderBy($builder, $select)
107 17
            ->compileLimit($builder, $select);
108 17
        return $builder;
109
    }
110
111
    /**
112
     * @param $builder \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Relations\Relation|\Illuminate\Database\Query\Builder
113
     * @param  Select $select
114
     * @return $this
115
     */
116 17
    protected function compileWhere($builder, Select $select)
117
    {
118 17
        $builder->where(function ($builder) use ($select) {
119 17
            foreach ($select->where() as $i => $group) {
120 10
                foreach ($group as $j => $condition) {
121 10
                    $builder->{$i !== 0 && $j === 0 ? 'orWhere' : 'where'}(
122 10
                        $this->transformPivotColumn($condition->left()),
123 10
                        $condition->comparator(),
124 10
                        $condition->right()
125
                    );
126
                }
127
            }
128 17
        });
129 17
        return $this;
130
    }
131
132
    /**
133
     * @param $builder \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Relations\Relation|\Illuminate\Database\Query\Builder
134
     * @param  Select $select
135
     * @return $this
136
     */
137 17
    protected function compileOrderBy($builder, Select $select)
138
    {
139 17
        foreach ($select->orders() as $order) {
140 17
            $builder->orderBy(...$order->toArray());
141
        }
142 17
        return $this;
143
    }
144
145
    /**
146
     * @param $builder \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Relations\Relation|\Illuminate\Database\Query\Builder
147
     * @param  Select $select
148
     * @return $this
149
     */
150 17
    protected function compileLimit($builder, Select $select)
151
    {
152 17
        $builder->limit($select->limit()->toInteger());
153 17
        return $this;
154
    }
155
156
    /**
157
     * We need to add columns explicitly for UNION ALL subjects
158
     * because BelongsToMany cannot handle them correctly.
159
     *
160
     * @param  \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Relations\Relation|\Illuminate\Database\Query\Builder $query
161
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Relations\Relation|\Illuminate\Database\Query\Builder
162
     */
163 10
    protected function addSelectForUnionAll($query)
164
    {
165 10
        static $invoker;
166 10
        if (!$invoker) {
167 1
            $invoker = function () {
168 2
                return $this->shouldSelect($this->getBaseQuery()->columns ? [] : ['*']);
0 ignored issues
show
Documentation Bug introduced by
The method getBaseQuery does not exist on object<mav3rick177\RapidPagination\Paginator>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
Documentation Bug introduced by
The method shouldSelect does not exist on object<mav3rick177\RapidPagination\Paginator>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
169 1
            };
170
        }
171 10
        return $query instanceof BelongsToMany
172 2
            ? $query->addSelect($invoker->bindTo($query, $query)->__invoke())
173 10
            : $query;
174
    }
175
176
    /**
177
     * We need to transform aliased columns into non-aliased form
178
     * because SQL standard does not allow column aliases in WHERE conditions.
179
     *
180
     * @param  string $column
181
     * @return string
182
     */
183 10
    protected function transformPivotColumn($column)
184
    {
185 10
        return $this->builder instanceof BelongsToMany && strpos($column, 'pivot_') === 0
186 1
            ? ($this->builder->getTable() . '.' . substr($column, 6))
187 10
            : $column;
188
    }
189
}
190