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.
Completed
Push — master ( 9e7309...ca86c4 )
by Aden
39:37 queued 06:18
created

ModelQuerying::query()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 23
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 23
rs 8.7972
cc 4
eloc 11
nc 6
nop 1
1
<?php
2
3
namespace LaravelFlare\Flare\Admin\Models\Traits;
4
5
trait ModelQuerying
6
{
7
    /**
8
     * Query
9
     * 
10
     * @var string
11
     */
12
    public $query;
13
14
    /**
15
     * Allows filtering of the default query, for instance:.
16
     *
17
     *      $queryFilter = [
18
     *                          'whereNotNull' => ['parent_id'],
19
     *                          'where' => ['name', 'John'],
20
     *                      ]
21
     *
22
     * Would result in an Eloquent query with the following scope:
23
     *     Model::whereNotNull('parent_id')->where('name', 'John')->get();
24
     *
25
     * Note: This queryFilter is not used for custom filters and
26
     * can also be overridden by setQueryFilter();
27
     * 
28
     * @var array
29
     */
30
    protected $queryFilter = [];
31
32
    /**
33
     * Any array of Filters.
34
     *
35
     * Filter should be setup in the same fashion as a default
36
     * $queryFilter is setup, however, inside an associative
37
     * array.
38
     *
39
     * The associative array is your filter 'action' and is 
40
     * used as the filter label (and converted to a URL safe
41
     * query parameter).
42
     * 
43
     * @var array
44
     */
45
    protected $filters = [];
46
47
    /**
48
     * The number of models to return for pagination.
49
     *
50
     * @var int
51
     */
52
    protected $perPage = 15;
53
54
    /**
55
     * Order By - Column/Attribute to OrderBy.
56
     *
57
     * Primary Key of Model by default
58
     * 
59
     * @var string
60
     */
61
    protected $orderBy;
62
63
    /**
64
     * Sort By - Either Desc or Asc.
65
     * 
66
     * @var string
67
     */
68
    protected $sortBy;
69
70
    /**
71
     * Finds an existing Model entry and sets it to the current model.
72
     * 
73
     * @param int $modelitemId
74
     * 
75
     * @return
76
     */
77
    public function find($modelitemId)
78
    {
79
        $this->model = $this->model->findOrFail($modelitemId);
80
81
        return $this->model;
82
    }
83
84
    /**
85
     * Returns Model Items, either all() or paginated().
86
     *
87
     * Filtered by any defined query filters ($queryFilter)
88
     * Ordered by Managed Model orderBy and sortBy methods
89
     * 
90
     * @return
91
     */
92
    public function items($count = false)
93
    {
94
        \DB::enableQueryLog();
95
        $this->query = $this->model->newQuery();
96
97
        return $this->query($count);
98
    }
99
100
    /**
101
     * Returns All Model Items, either all() or paginated().
102
     *
103
     * Filtered by any defined query filters ($queryFilter)
104
     * Ordered by Managed Model orderBy and sortBy methods
105
     * 
106
     * @return
107
     */
108 View Code Duplication
    public function allItems($count = false)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
109
    {
110
        if (!$this->hasSoftDeleting()) {
0 ignored issues
show
Bug introduced by
It seems like hasSoftDeleting() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
111
            throw new \Exception('Model does not have Soft Deleting');
112
        }
113
114
        $this->query = $this->model->newQuery()->withTrashed();
115
116
        return $this->query($count);
117
    }
118
119
    /**
120
     * Returns Model Items, either all() or paginated().
121
     *
122
     * Filtered by any defined query filters ($queryFilter)
123
     * Ordered by Managed Model orderBy and sortBy methods
124
     * 
125
     * @return
126
     */
127 View Code Duplication
    public function onlyTrashedItems($count = false)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
128
    {
129
        if (!$this->hasSoftDeleting()) {
0 ignored issues
show
Bug introduced by
It seems like hasSoftDeleting() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
130
            throw new \Exception('Model does not have Soft Deleting');
131
        }
132
133
        $this->query = $this->model->newQuery()->onlyTrashed();
134
135
        return $this->query($count);
136
    }
137
138
    /**
139
     * Performs the Model Query
140
     * 
141
     * @return \Illuminate\Database\Eloquent\Collection
142
     */
143
    private function query($count)
144
    {
145
        $this->applyQueryFilters();
146
147
        if ($this->orderBy()) {
148
            $this->query = $this->query->orderBy(
149
                                $this->orderBy(),
150
                                $this->sortBy()
151
                            );
152
        }
153
154
        //dd(\DB::getQueryLog());
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
155
156
        if ($count) {
157
            return $this->query->count();
158
        }
159
160
        if ($this->perPage > 0) {
161
            return $this->query->paginate($this->perPage);
162
        }
163
164
        return $this->query->get();
165
    }
166
167
    /**
168
     * Return Totals of All, With Trashed and Only Trashed
169
     * 
170
     * @return array
171
     */
172
    public function totals()
173
    {
174
        if ($this->hasSoftDeleting()) {
0 ignored issues
show
Bug introduced by
It seems like hasSoftDeleting() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
175
            return [
176
                        'all' => $this->items($count = true),
177
                        'with_trashed' => $this->allItems($count = true),
178
                        'only_trashed' => $this->onlyTrashedItems($count = true),
179
                    ];
180
        }
181
182
        return ['all' => $this->model->count()];
183
    }
184
185
    /**
186
     * Return Managed Model OrderBy.
187
     *
188
     * Primary key is default.
189
     *
190
     * @return string
191
     */
192
    public function orderBy()
193
    {
194
        if (\Request::input('order')) {
195
            return \Request::input('order');
196
        }
197
198
        if ($this->orderBy) {
199
            return $this->orderBy;
200
        }
201
    }
202
203
    /**
204
     * Return Managed Model SortBy (Asc or Desc).
205
     *
206
     * Descending is default.
207
     * 
208
     * @return string
209
     */
210
    public function sortBy()
211
    {
212
        if (\Request::input('sort')) {
213
            return \Request::input('sort');
214
        }
215
216
        if ($this->sortBy == 'asc') {
217
            return 'asc';
218
        }
219
220
        return 'desc';
221
    }
222
223
    /**
224
     * Get the number of models to return per page.
225
     *
226
     * @return int
227
     */
228
    public function getPerPage()
229
    {
230
        return $this->perPage;
231
    }
232
233
    /**
234
     * Set the number of models to return per page.
235
     *
236
     * @param int $perPage
237
     */
238
    public function setPerPage($perPage)
239
    {
240
        $this->perPage = $perPage;
241
    }
242
243
    /**
244
     * Apply the Query Filters
245
     * 
246
     * @return 
247
     */
248
    private function applyQueryFilters()
249
    {
250
        if (is_array($this->queryFilter())) {
251
            $this->createQueryFilter();
252
        } else {
253
            $this->queryFilter();
0 ignored issues
show
Unused Code introduced by
The call to the method LaravelFlare\Flare\Admin...Querying::queryFilter() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
254
        }
255
256
        $this->queryFilterRequest();
257
    }
258
259
    private function queryFilterRequest()
260
    {
261
        if (!$safeFilter = \Request::get('filter')) {
262
            return false;
263
        } 
264
265
        if (!isset($this->safeFilters()[$safeFilter])) {
266
            return false;
267
        }
268
269
        return $this->query = $this->filters()[$this->safeFilters()[$safeFilter]];
270
    }
271
272
    /**
273
     * Create the Query Filter from Array
274
     * 
275
     * @return
276
     */
277
    private function createQueryFilter()
278
    {
279
        if (count($this->queryFilter()) > 0) {
280
            foreach ($this->queryFilter() as $filter => $parameters) {
281
                if (!is_array($parameters)) {
282
                    $parameters = [$parameters];
283
                }
284
                $this->query = call_user_func_array([$this->query, $filter], $parameters);
285
            }
286
        }
287
    }
288
289
    /**
290
     * Access the Query Filter
291
     * 
292
     * @return 
293
     */
294
    public function queryFilter()
295
    {
296
        return $this->queryFilter;
297
    }
298
299
    /**
300
     * Access the Query Filter Options
301
     * 
302
     * @return 
303
     */
304
    public function filters()
305
    {
306
        return $this->filters;
307
    }
308
309
    /**
310
     * Associative array of safe filter names to 
311
     * their corresponding normal counterpart.
312
     * 
313
     * @return 
314
     */
315
    public function safeFilters()
316
    {
317
        $filters = [];
318
319
        foreach ($this->filters() as $filterName => $query) {
320
            $filters[str_slug($filterName)] = $filterName;
321
        }
322
323
        return $filters;
324
    }
325
326
    /**
327
     * Set the Query Filter
328
     * 
329
     * @param array $filter
330
     *
331
     * @return void
332
     */
333
    public function setQueryFilter($filter = [])
334
    {
335
        $this->queryFilter = $filter;
336
    }
337
}
338