GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

RequestCriteria::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Milkmeowo\Framework\Base\Repositories\Criteria;
4
5
use Illuminate\Http\Request;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Database\Eloquent\Builder;
8
use Prettus\Repository\Contracts\CriteriaInterface;
9
use Prettus\Repository\Contracts\RepositoryInterface;
10
11
class RequestCriteria implements CriteriaInterface
12
{
13
    /**
14
     * @var \Illuminate\Http\Request
15
     */
16
    protected $request;
17
18
    /**
19
     * RequestCriteria constructor.
20
     *
21
     * @param Request $request
22
     */
23
    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...
24
    {
25
        $this->request = $request;
26
    }
27
28
    /**
29
     * Apply criteria in query repository.
30
     *
31
     * @param         Builder|Model $model
32
     * @param RepositoryInterface   $repository
33
     *
34
     * @return mixed
35
     * @throws \Exception
36
     */
37
    public function apply($model, RepositoryInterface $repository)
38
    {
39
        $fieldsSearchable = $repository->getFieldsSearchable();
40
        $search = $this->request->get(config('repository.criteria.params.search', 'search'), null);
41
        $searchFields = $this->request->get(config('repository.criteria.params.searchFields', 'searchFields'), null);
42
        $filter = $this->request->get(config('repository.criteria.params.filter', 'filter'), null);
43
        $orderBy = $this->request->get(config('repository.criteria.params.orderBy', 'orderBy'), null);
44
        $sortedBy = $this->request->get(config('repository.criteria.params.sortedBy', 'sortedBy'), 'asc');
45
        $with = $this->request->get(config('repository.criteria.params.with', 'with'), null);
46
        $sortedBy = ! empty($sortedBy) ? $sortedBy : 'asc';
47
48
        if ($search && is_array($fieldsSearchable) && count($fieldsSearchable)) {
49
            $searchFields = is_array($searchFields) || is_null($searchFields) ? $searchFields : explode(';',
50
                $searchFields);
51
            $fields = $this->parserFieldsSearch($fieldsSearchable, $searchFields);
52
            $isFirstField = true;
53
            $searchData = $this->parserSearchData($search);
54
            $search = $this->parserSearchValue($search);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $search is correct as $this->parserSearchValue($search) (which targets Milkmeowo\Framework\Base...ia::parserSearchValue()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
55
            $modelForceAndWhere = false;
56
57
            $model = $model->where(function ($query) use (
0 ignored issues
show
Bug introduced by
The method where does only exist in Illuminate\Database\Eloquent\Builder, but not in Illuminate\Database\Eloquent\Model.

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...
58
                $fields,
59
                $search,
60
                $searchData,
61
                $isFirstField,
62
                $modelForceAndWhere
63
            ) {
64
                /* @var Builder $query */
65
66
                foreach ($fields as $field => $condition) {
67
                    if (is_numeric($field)) {
68
                        $field = $condition;
69
                        $condition = '=';
70
                    }
71
72
                    $value = null;
73
74
                    $condition = trim(strtolower($condition));
75
76
                    if (isset($searchData[$field])) {
77
                        $value = ($condition == 'like' || $condition == 'ilike') ? "%{$searchData[$field]}%" : $searchData[$field];
78
                    } else {
79
                        if (! is_null($search)) {
80
                            $value = ($condition == 'like' || $condition == 'ilike') ? "%{$search}%" : $search;
81
                        }
82
                    }
83
84
                    $relation = null;
85
                    if (stripos($field, '.')) {
86
                        $explode = explode('.', $field);
87
                        $field = array_pop($explode);
88
                        $relation = implode('.', $explode);
89
                    }
90
                    $modelTableName = $query->getModel()->getTable();
91
                    if ($isFirstField || $modelForceAndWhere) {
92 View Code Duplication
                        if (! is_null($value)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
93
                            if (! is_null($relation)) {
94
                                $query->whereHas($relation, function ($query) use ($field, $condition, $value) {
95
                                    $query->where($field, $condition, $value);
96
                                });
97
                            } else {
98
                                $query->where($modelTableName.'.'.$field, $condition, $value);
99
                            }
100
                            $isFirstField = false;
0 ignored issues
show
Bug introduced by
Consider using a different name than the imported variable $isFirstField, or did you forget to import by reference?

It seems like you are assigning to a variable which was imported through a use statement which was not imported by reference.

For clarity, we suggest to use a different name or import by reference depending on whether you would like to have the change visibile in outer-scope.

Change not visible in outer-scope

$x = 1;
$callable = function() use ($x) {
    $x = 2; // Not visible in outer scope. If you would like this, how
            // about using a different variable name than $x?
};

$callable();
var_dump($x); // integer(1)

Change visible in outer-scope

$x = 1;
$callable = function() use (&$x) {
    $x = 2;
};

$callable();
var_dump($x); // integer(2)
Loading history...
101
                        }
102 View Code Duplication
                    } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
103
                        if (! is_null($value)) {
104
                            if (! is_null($relation)) {
105
                                $query->orWhereHas($relation, function ($query) use ($field, $condition, $value) {
106
                                    $query->where($field, $condition, $value);
107
                                });
108
                            } else {
109
                                $query->orWhere($modelTableName.'.'.$field, $condition, $value);
110
                            }
111
                        }
112
                    }
113
                }
114
            });
115
        }
116
117
        if (isset($orderBy) && ! empty($orderBy)) {
118
            $split = explode('|', $orderBy);
119
            if (count($split) > 1) {
120
                /*
121
                 * ex.
122
                 * products|description -> join products on current_table.product_id = products.id order by description
123
                 *
124
                 * products:custom_id|products.description -> join products on current_table.custom_id = products.id order
125
                 * by products.description (in case both tables have same column name)
126
                 */
127
                $table = $model->getModel()->getTable();
128
                $sortTable = $split[0];
129
                $sortColumn = $split[1];
130
131
                $split = explode(':', $sortTable);
132
                if (count($split) > 1) {
133
                    $sortTable = $split[0];
134
                    $keyName = $table.'.'.$split[1];
135
                } else {
136
                    /*
137
                     * If you do not define which column to use as a joining column on current table, it will
138
                     * use a singular of a join table appended with _id
139
                     *
140
                     * ex.
141
                     * products -> product_id
142
                     */
143
                    $prefix = rtrim($sortTable, 's');
144
                    $keyName = $table.'.'.$prefix.'_id';
145
                }
146
147
                $model = $model->leftJoin($sortTable, $keyName, '=', $sortTable.'.id')->orderBy($sortColumn,
148
                    $sortedBy)->addSelect($table.'.*');
149
            } else {
150
                $model = $model->orderBy($orderBy, $sortedBy);
151
            }
152
        }
153
154
        if (isset($filter) && ! empty($filter)) {
155
            if (is_string($filter)) {
156
                $filter = explode(';', $filter);
157
            }
158
159
            $model = $model->select($filter);
160
        }
161
162
        if ($with) {
163
            $with = explode(';', $with);
164
            $model = $model->with($with);
165
        }
166
167
        return $model;
168
    }
169
170
    /**
171
     * @param array      $fields
172
     * @param array|null $searchFields
173
     *
174
     * @return array
175
     * @throws \Exception
176
     */
177
    protected function parserFieldsSearch(array $fields = [], array $searchFields = null)
178
    {
179
        if (! is_null($searchFields) && count($searchFields)) {
180
            $acceptedConditions = config('repository.criteria.acceptedConditions', [
181
                '=',
182
                'like',
183
            ]);
184
            $originalFields = $fields;
185
            $fields = [];
186
187
            foreach ($searchFields as $index => $field) {
188
                $field_parts = explode(':', $field);
189
                $temporaryIndex = array_search($field_parts[0], $originalFields);
190
191
                if (count($field_parts) == 2) {
192
                    if (in_array($field_parts[1], $acceptedConditions)) {
193
                        unset($originalFields[$temporaryIndex]);
194
                        $field = $field_parts[0];
195
                        $condition = $field_parts[1];
196
                        $originalFields[$field] = $condition;
197
                        $searchFields[$index] = $field;
198
                    }
199
                }
200
            }
201
202
            foreach ($originalFields as $field => $condition) {
203
                if (is_numeric($field)) {
204
                    $field = $condition;
205
                    $condition = '=';
206
                }
207
                if (in_array($field, $searchFields)) {
208
                    $fields[$field] = $condition;
209
                }
210
            }
211
212
            if (count($fields) == 0) {
213
                throw new \Exception(trans('repository::criteria.fields_not_accepted',
214
                    ['field' => implode(',', $searchFields)]));
215
            }
216
        }
217
218
        return $fields;
219
    }
220
221
    /**
222
     * @param $search
223
     *
224
     * @return array
225
     */
226
    protected function parserSearchData($search)
227
    {
228
        $searchData = [];
229
230
        if (stripos($search, ':')) {
231
            $fields = explode(';', $search);
232
233
            foreach ($fields as $row) {
234
                try {
235
                    list($field, $value) = explode(':', $row);
236
                    $searchData[$field] = $value;
237
                } catch (\Exception $e) {
238
                    //Surround offset error
239
                }
240
            }
241
        }
242
243
        return $searchData;
244
    }
245
246
    /**
247
     * @param $search
248
     *
249
     * @return null
250
     */
251
    protected function parserSearchValue($search)
252
    {
253
        if (stripos($search, ';') || stripos($search, ':')) {
254
            $values = explode(';', $search);
255
            foreach ($values as $value) {
256
                $s = explode(':', $value);
257
                if (count($s) == 1) {
258
                    return $s[0];
259
                }
260
            }
261
262
            return;
263
        }
264
265
        return $search;
266
    }
267
}
268