Passed
Push β€” feature/optimize ( 6201d6...123ace )
by Fu
03:01
created

RequestCriteria::setSearchDataValue()   A

Complexity

Conditions 6
Paths 4

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 11
rs 9.2222
c 0
b 0
f 0
cc 6
nc 4
nop 3
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: guoliang
5
 * Date: 2019/3/11
6
 * Time: 上午10:11
7
 */
8
9
namespace Modules\Core\Criteria;
10
11
use Exception;
12
use Illuminate\Database\Eloquent\Builder;
13
use Illuminate\Database\Eloquent\Model;
14
use Illuminate\Http\Request;
15
use Prettus\Repository\Contracts\CriteriaInterface;
16
use Prettus\Repository\Contracts\RepositoryInterface;
17
18
class RequestCriteria implements CriteriaInterface
19
{
20
    /**
21
     * @var \Illuminate\Http\Request
22
     */
23
    protected $request;
24
    /**
25
     * @var \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model
26
     */
27
    private $model;
28
    private $search;
29
    private $searchData;
30
    private $searchFields;
31
    private $isFirstField = true;
32
    private $modelForceAndWhere;
33
    private $fieldsSearchable;
34
    private $fields;
35
    private $filter;
36
    private $orderBy;
37
    private $sortedBy;
38
    private $with;
39
    private $searchJoin;
40
    private $acceptedConditions;
41
    private $originalFields;
42
43
44
    public function __construct(Request $request)
45
    {
46
        $this->request = $request;
47
    }
48
49
    /**
50
     * Apply criteria in query repository
51
     *
52
     * @param Builder|Model $model
53
     * @param RepositoryInterface $repository
54
     *
55
     * @return mixed
56
     * @throws \Exception
57
     */
58
    public function apply($model, RepositoryInterface $repository)
59
    {
60
        $this->model = $model;
61
        $this->fieldsSearchable = $repository->getFieldsSearchable();
62
        $this->search = $this->request->get(config('repository.criteria.params.search', 'search'), null);
63
        $this->searchFields =
64
            $this->request->get(config('repository.criteria.params.searchFields', 'searchFields'), null);
65
        $this->filter = $this->request->get(config('repository.criteria.params.filter', 'filter'), null);
66
        $this->orderBy = $this->request->get(config('repository.criteria.params.orderBy', 'orderBy'), null);
67
        $this->sortedBy = $this->request->get(config('repository.criteria.params.sortedBy', 'sortedBy'), 'asc');
68
        $this->with = $this->request->get(config('repository.criteria.params.with', 'with'), null);
69
        $this->searchJoin = $this->request->get(config('repository.criteria.params.searchJoin', 'searchJoin'), null);
70
        $this->sortedBy = !empty($sortedBy) ? $sortedBy : 'asc';
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $sortedBy seems to never exist and therefore empty should always be true.
Loading history...
71
        $this->acceptedConditions = config('repository.criteria.acceptedConditions', ['=', 'like']);
72
73
        $this->parserSearch();
74
        $this->parserOrderBy();
75
        $this->parserFilter();
76
        $this->parserWith();
77
78
        return $this->model;
79
    }
80
81
    protected function parserSearchData()
82
    {
83
        $searchData = [];
84
85
        if (stripos($this->search, ':')) {
86
            $fields = explode(';', $this->search);
87
88
            foreach ($fields as $row) {
89
                try {
90
                    list($field, $value) = explode(':', $row);
91
                    $searchData[$field] = $value;
92
                } catch (Exception $e) {
93
                    //Surround offset error
94
                }
95
            }
96
        }
97
98
        $this->searchData = $searchData;
99
    }
100
101
    protected function parserSearchValue()
102
    {
103
        if (stripos($this->search, ';') || stripos($this->search, ':')) {
104
            $values = explode(';', $this->search);
105
            foreach ($values as $value) {
106
                $s = explode(':', $value);
107
                if (count($s) == 1) {
108
                    $this->search = $s[0];
109
                }
110
            }
111
112
            $this->search = null;
113
        }
114
    }
115
116
    /**
117
     * @throws \Exception
118
     */
119
    protected function parserFieldsSearch()
120
    {
121
        $this->parserSearchFields();
122
        $fields = $this->fieldsSearchable;
123
124
        if (!is_null($this->searchFields) && count($this->searchFields)) {
125
126
            $this->parserOriginalFields();
127
128
            $fields = [];
129
130
            foreach ($this->originalFields as $field => $condition) {
131
                if (is_numeric($field)) {
132
                    $field = $condition;
133
                    $condition = "=";
134
                }
135
                if (in_array($field, $this->searchFields)) {
0 ignored issues
show
Bug introduced by
It seems like $this->searchFields can also be of type null; however, parameter $haystack of in_array() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

135
                if (in_array($field, /** @scrutinizer ignore-type */ $this->searchFields)) {
Loading history...
136
                    $fields[$field] = $condition;
137
                }
138
            }
139
140
            if (count($fields) == 0) {
141
                throw new Exception(trans('repository::criteria.fields_not_accepted', ['field' => implode(',', $this->searchFields)]));
0 ignored issues
show
Bug introduced by
It seems like $this->searchFields can also be of type null; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

141
                throw new Exception(trans('repository::criteria.fields_not_accepted', ['field' => implode(',', /** @scrutinizer ignore-type */ $this->searchFields)]));
Loading history...
Bug introduced by
It seems like trans('repository::crite... $this->searchFields))) can also be of type array; however, parameter $message of Exception::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

141
                throw new Exception(/** @scrutinizer ignore-type */ trans('repository::criteria.fields_not_accepted', ['field' => implode(',', $this->searchFields)]));
Loading history...
142
            }
143
144
        }
145
146
        $this->fields = $fields;
147
    }
148
149
    protected function parserOrderBy()
150
    {
151
        if (isset($this->orderBy) && !empty($this->orderBy)) {
152
            $split = explode('|', $this->orderBy);
153
            if (count($split) > 1) {
154
                $table = $this->model->getModel()->getTable();
155
                $sortTable = $split[0];
156
                $sortColumn = $split[1];
157
158
                $split = explode(':', $sortTable);
159
                if (count($split) > 1) {
160
                    $sortTable = $split[0];
161
                    $keyName = $table.'.'.$split[1];
162
                } else {
163
                    $prefix = str_singular($sortTable);
0 ignored issues
show
Deprecated Code introduced by
The function str_singular() has been deprecated: Str::singular() should be used directly instead. Will be removed in Laravel 5.9. ( Ignorable by Annotation )

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

163
                    $prefix = /** @scrutinizer ignore-deprecated */ str_singular($sortTable);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
164
                    $keyName = $table.'.'.$prefix.'_id';
165
                }
166
167
                $this->model = $this->model->leftJoin($sortTable, $keyName, '=', $sortTable.'.id')
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->model->leftJoin($...ddSelect($table . '.*') can also be of type Illuminate\Database\Query\Builder. However, the property $model is declared as type Illuminate\Database\Eloq...Database\Eloquent\Model. 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...
168
                                           ->orderBy($sortColumn, $this->sortedBy)
169
                                           ->addSelect($table.'.*');
170
            } else {
171
                $this->model = $this->model->orderBy($this->orderBy, $this->sortedBy);
172
            }
173
        }
174
    }
175
176
    protected function parserFilter()
177
    {
178
        if (isset($this->filter) && !empty($this->filter)) {
179
            if (is_string($this->filter)) {
180
                $this->filter = explode(';', $this->filter);
181
            }
182
183
            $this->model = $this->model->select($this->filter);
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->model->select($this->filter) can also be of type Illuminate\Database\Query\Builder. However, the property $model is declared as type Illuminate\Database\Eloq...Database\Eloquent\Model. 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...
184
        }
185
    }
186
187
    protected function parserWith()
188
    {
189
        if ($this->with) {
190
            $this->with = explode(';', $this->with);
191
            $this->model = $this->model->with($this->with);
192
        }
193
    }
194
195
    /**
196
     * @throws \Exception
197
     */
198
    protected function parserSearch()
199
    {
200
        if ($this->search && is_array($this->fieldsSearchable) && count($this->fieldsSearchable)) {
201
202
            $this->parserFieldsSearch();
203
            $this->parserSearchData();
204
            $this->parserSearchValue();
205
206
            $this->modelForceAndWhere = strtolower($this->searchJoin) === 'and';
207
208
            foreach ($this->fields as $field => $condition) {
209
210
                if (is_numeric($field)) {
211
                    $field = $condition;
212
                    $condition = "=";
213
                }
214
215
                $value = null;
216
217
                $condition = trim(strtolower($condition));
218
219
                if (isset($this->searchData[$field])) {
220
                    $value = $this->searchData[$field];
221
                    if ($condition == "like" || $condition == "ilike") {
222
                        $value = "%{$value}%";
223
                    }
224
                    if ($condition == "in" || $condition == "between" || $condition == "cross") {
225
                        $value = explode(',', $value);
226
                    }
227
                } else {
228
                    if (!is_null($this->search)) {
229
                        $value = $this->search;
230
                        if ($condition == "like" || $condition == "ilike") {
231
                            $value = "%{$value}%";
232
                        }
233
                        if ($condition == "in" || $condition == "between" || $condition == "cross") {
234
                            $value = explode(',', $value);
235
                        }
236
                    }
237
                }
238
239
                $relation = null;
240
                if (stripos($field, '.')) {
241
                    $explode = explode('.', $field);
242
                    $field = array_pop($explode);
243
                    $relation = implode('.', $explode);
244
                }
245
                $modelTableName = $this->model->getModel()->getTable();
246
                if ($this->isFirstField || $this->modelForceAndWhere) {
247
                    if (!is_null($value)) {
248
                        if (!is_null($relation)) {
249
                            $this->model = $this->model->whereHas($relation, function (Builder $query) use (
250
                                $field,
251
                                $condition,
252
                                $value
253
                            ) {
254
                                if ($condition == 'in') {
255
                                    $query->whereIn($field, $value);
256
                                } elseif ($condition == 'between') {
257
                                    $query->whereBetween($field, $value);
258
                                } elseif ($condition == 'cross') {
259
                                    $query->where(function (Builder $query) use ($field, $value) {
260
                                        $query->where(function (Builder $query) use ($field, $value) {
261
                                            $query->where("{$field}_min", '<=', $value[0])
262
                                                  ->where("{$field}_max", '>=', $value[1]);
263
                                        })->orWhere(function (Builder $query) use ($field, $value) {
264
                                            $query->where("{$field}_min", '<=', $value[0])
265
                                                  ->where("{$field}_max", '>=', $value[0]);
266
                                        })->orWhere(function (Builder $query) use ($field, $value) {
267
                                            $query->where("{$field}_min", '>=', $value[0])
268
                                                  ->where("{$field}_max", '<=', $value[1]);
269
                                        })->orWhere(function (Builder $query) use ($field, $value) {
270
                                            $query->where("{$field}_min", '>=', $value[0])
271
                                                  ->where("{$field}_max", '>=', $value[1])
272
                                                  ->where("{$field}_min", '<=', $value[1]);
273
                                        });
274
                                    });
275
                                } else {
276
                                    $query->where($field, $condition, $value);
277
                                }
278
                            });
279
                        } else {
280
                            if ($condition == 'in') {
281
                                $this->model = $this->model->whereIn($field, $value);
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->model->whereIn($field, $value) can also be of type Illuminate\Database\Query\Builder. However, the property $model is declared as type Illuminate\Database\Eloq...Database\Eloquent\Model. 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...
282
                            } elseif ($condition == 'between') {
283
                                $this->model = $this->model->whereBetween($field, $value);
284
                            } elseif ($condition == 'cross') {
285
                                $this->model = $this->model->where(function (Builder $query) use ($field, $value) {
286
                                    $query->where(function (Builder $query) use ($field, $value) {
287
                                        $query->where("{$field}_min", '<=', $value[0])
288
                                              ->where("{$field}_max", '>=', $value[1]);
289
                                    })->orWhere(function (Builder $query) use ($field, $value) {
290
                                        $query->where("{$field}_min", '<=', $value[0])
291
                                              ->where("{$field}_max", '>=', $value[0]);
292
                                    })->orWhere(function (Builder $query) use ($field, $value) {
293
                                        $query->where("{$field}_min", '>=', $value[0])
294
                                              ->where("{$field}_max", '<=', $value[1]);
295
                                    })->orWhere(function (Builder $query) use ($field, $value) {
296
                                        $query->where("{$field}_min", '>=', $value[0])
297
                                              ->where("{$field}_max", '>=', $value[1])
298
                                              ->where("{$field}_min", '<=', $value[1]);
299
                                    });
300
                                });
301
                            } else {
302
                                $this->model = $this->model->where($field, $condition, $value);
303
                            }
304
                        }
305
                        $this->isFirstField = false;
306
                    }
307
                } else {
308
                    if (!is_null($value)) {
309
                        if (!is_null($relation)) {
310
                            $this->model = $this->model->orWhereHas($relation, function (Builder $query) use (
311
                                $field,
312
                                $condition,
313
                                $value
314
                            ) {
315
                                if ($condition == 'in') {
316
                                    $query->whereIn($field, $value);
317
                                } elseif ($condition == 'between') {
318
                                    $query->whereBetween($field, $value);
319
                                } elseif ($condition == 'cross') {
320
                                    $query->where(function (Builder $query) use ($field, $value) {
321
                                        $query->where(function (Builder $query) use ($field, $value) {
322
                                            $query->where("{$field}_min", '<=', $value[0])
323
                                                  ->where("{$field}_max", '>=', $value[1]);
324
                                        })->orWhere(function (Builder $query) use ($field, $value) {
325
                                            $query->where("{$field}_min", '<=', $value[0])
326
                                                  ->where("{$field}_max", '>=', $value[0]);
327
                                        })->orWhere(function (Builder $query) use ($field, $value) {
328
                                            $query->where("{$field}_min", '>=', $value[0])
329
                                                  ->where("{$field}_max", '<=', $value[1]);
330
                                        })->orWhere(function (Builder $query) use ($field, $value) {
331
                                            $query->where("{$field}_min", '>=', $value[0])
332
                                                  ->where("{$field}_max", '>=', $value[1])
333
                                                  ->where("{$field}_min", '<=', $value[1]);
334
                                        });
335
                                    });
336
                                } else {
337
                                    $query->where($field, $condition, $value);
338
                                }
339
                            });
340
                        } else {
341
                            if ($condition == 'in') {
342
                                $this->model = $this->model->orWhereIn($modelTableName.'.'.$field, $value);
343
                            } elseif ($condition == 'between') {
344
                                $this->model = $this->model->orWhereBetween($modelTableName.'.'.$field, $value);
345
                            } elseif ($condition == 'cross') {
346
                                $this->model = $this->model->orWhere(function (Builder $query) use ($field, $value) {
347
                                    $query->where(function (Builder $query) use ($field, $value) {
348
                                        $query->where("{$field}_min", '<=', $value[0])
349
                                              ->where("{$field}_max", '>=', $value[1]);
350
                                    })->orWhere(function (Builder $query) use ($field, $value) {
351
                                        $query->where("{$field}_min", '<=', $value[0])
352
                                              ->where("{$field}_max", '>=', $value[0]);
353
                                    })->orWhere(function (Builder $query) use ($field, $value) {
354
                                        $query->where("{$field}_min", '>=', $value[0])
355
                                              ->where("{$field}_max", '<=', $value[1]);
356
                                    })->orWhere(function (Builder $query) use ($field, $value) {
357
                                        $query->where("{$field}_min", '>=', $value[0])
358
                                              ->where("{$field}_max", '>=', $value[1])
359
                                              ->where("{$field}_min", '<=', $value[1]);
360
                                    });
361
                                });
362
                            } else {
363
                                $this->model = $this->model->orWhere($modelTableName.'.'.$field, $condition, $value);
364
                            }
365
                        }
366
                    }
367
                }
368
            }
369
        }
370
    }
371
372
    protected function parserSearchFields()
373
    {
374
        if (!is_array($this->searchFields) && !is_null($this->searchFields)) {
375
            $this->searchFields = explode(';', $this->searchFields);
376
        }
377
    }
378
379
    protected function parserOriginalFields()
380
    {
381
        $this->originalFields = $this->fieldsSearchable;
382
383
        foreach ($this->searchFields as $index => $field) {
384
            $field_parts = explode(':', $field);
385
            $temporaryIndex = array_search($field_parts[0], $this->originalFields);
386
387
            if (count($field_parts) == 2) {
388
                if (in_array($field_parts[1], $this->acceptedConditions)) {
389
                    unset($this->originalFields[$temporaryIndex]);
390
                    $field = $field_parts[0];
391
                    $condition = $field_parts[1];
392
                    $this->originalFields[$field] = $condition;
393
                    $this->searchFields[$index] = $field;
394
                }
395
            }
396
        }
397
    }
398
}
399