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 ( c11a02...1afb84 )
by Aden
05:09
created

ModelQuerying   A

Complexity

Total Complexity 34

Size/Duplication

Total Lines 334
Duplicated Lines 5.99 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 3
Bugs 1 Features 0
Metric Value
wmc 34
c 3
b 1
f 0
lcom 1
cbo 1
dl 20
loc 334
rs 9.2

17 Methods

Rating   Name   Duplication   Size   Complexity  
A totals() 0 12 2
A getPerPage() 0 4 1
A setPerPage() 0 4 1
A applyQueryFilters() 0 10 2
A find() 0 6 1
A items() 0 7 1
A allItems() 10 10 2
A onlyTrashedItems() 10 10 2
A query() 0 21 4
A orderBy() 0 10 3
A sortBy() 0 12 3
A queryFilterRequest() 0 12 3
A createQueryFilter() 0 11 4
A queryFilter() 0 4 1
A filters() 0 4 1
A safeFilters() 0 10 2
A setQueryFilter() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace LaravelFlare\Flare\Admin\Models\Traits;
4
5
use Request;
6
7
trait ModelQuerying
8
{
9
    /**
10
     * Query.
11
     * 
12
     * @var string
13
     */
14
    public $query;
15
16
    /**
17
     * Allows filtering of the default query, for instance:.
18
     *
19
     *      $queryFilter = [
20
     *                          'whereNotNull' => ['parent_id'],
21
     *                          'where' => ['name', 'John'],
22
     *                      ]
23
     *
24
     * Would result in an Eloquent query with the following scope:
25
     *     Model::whereNotNull('parent_id')->where('name', 'John')->get();
26
     *
27
     * Note: This queryFilter is not used for custom filters and
28
     * can also be overridden by setQueryFilter();
29
     * 
30
     * @var array
31
     */
32
    protected $queryFilter = [];
33
34
    /**
35
     * Any array of Filters.
36
     *
37
     * Filter should be setup in the same fashion as a default
38
     * $queryFilter is setup, however, inside an associative
39
     * array.
40
     *
41
     * The associative array is your filter 'action' and is 
42
     * used as the filter label (and converted to a URL safe
43
     * query parameter).
44
     * 
45
     * @var array
46
     */
47
    protected $filters = [];
48
49
    /**
50
     * The number of models to return for pagination.
51
     *
52
     * @var int
53
     */
54
    protected $perPage = 15;
55
56
    /**
57
     * Order By - Column/Attribute to OrderBy.
58
     *
59
     * Primary Key of Model by default
60
     * 
61
     * @var string
62
     */
63
    protected $orderBy;
64
65
    /**
66
     * Sort By - Either Desc or Asc.
67
     * 
68
     * @var string
69
     */
70
    protected $sortBy;
71
72
    /**
73
     * Finds an existing Model entry and sets it to the current model.
74
     * 
75
     * @param int $modelitemId
76
     * 
77
     * @return
78
     */
79
    public function find($modelitemId)
80
    {
81
        $this->model = $this->model->findOrFail($modelitemId);
82
83
        return $this->model;
84
    }
85
86
    /**
87
     * Returns Model Items, either all() or paginated().
88
     *
89
     * Filtered by any defined query filters ($queryFilter)
90
     * Ordered by Managed Model orderBy and sortBy methods
91
     * 
92
     * @return
93
     */
94
    public function items($count = false)
95
    {
96
        \DB::enableQueryLog();
97
        $this->query = $this->model->newQuery();
98
99
        return $this->query($count);
100
    }
101
102
    /**
103
     * Returns All Model Items, either all() or paginated().
104
     *
105
     * Filtered by any defined query filters ($queryFilter)
106
     * Ordered by Managed Model orderBy and sortBy methods
107
     * 
108
     * @return
109
     */
110 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...
111
    {
112
        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...
113
            throw new \Exception('Model does not have Soft Deleting');
114
        }
115
116
        $this->query = $this->model->newQuery()->withTrashed();
117
118
        return $this->query($count);
119
    }
120
121
    /**
122
     * Returns Model Items, either all() or paginated().
123
     *
124
     * Filtered by any defined query filters ($queryFilter)
125
     * Ordered by Managed Model orderBy and sortBy methods
126
     * 
127
     * @return
128
     */
129 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...
130
    {
131
        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...
132
            throw new \Exception('Model does not have Soft Deleting');
133
        }
134
135
        $this->query = $this->model->newQuery()->onlyTrashed();
136
137
        return $this->query($count);
138
    }
139
140
    /**
141
     * Performs the Model Query.
142
     * 
143
     * @return \Illuminate\Database\Eloquent\Collection
144
     */
145
    private function query($count)
146
    {
147
        $this->applyQueryFilters();
148
149
        if ($this->orderBy()) {
150
            $this->query = $this->query->orderBy(
151
                                $this->orderBy(),
152
                                $this->sortBy()
153
                            );
154
        }
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
    /**
260
     * Apply the Query Filters specific to this Request.
261
     * 
262
     * @return 
263
     */
264
    private function queryFilterRequest()
265
    {
266
        if (!$safeFilter = Request::get('filter')) {
267
            return false;
268
        }
269
270
        if (!isset($this->safeFilters()[$safeFilter])) {
271
            return false;
272
        }
273
274
        return $this->query = $this->filters()[$this->safeFilters()[$safeFilter]];
275
    }
276
277
    /**
278
     * Create the Query Filter from Array.
279
     * 
280
     * @return
281
     */
282
    private function createQueryFilter()
283
    {
284
        if (count($this->queryFilter()) > 0) {
285
            foreach ($this->queryFilter() as $filter => $parameters) {
286
                if (!is_array($parameters)) {
287
                    $parameters = [$parameters];
288
                }
289
                $this->query = call_user_func_array([$this->query, $filter], $parameters);
290
            }
291
        }
292
    }
293
294
    /**
295
     * Access the Query Filter.
296
     * 
297
     * @return 
298
     */
299
    public function queryFilter()
300
    {
301
        return $this->queryFilter;
302
    }
303
304
    /**
305
     * Access the Query Filter Options.
306
     * 
307
     * @return 
308
     */
309
    public function filters()
310
    {
311
        return $this->filters;
312
    }
313
314
    /**
315
     * Associative array of safe filter names to 
316
     * their corresponding normal counterpart.
317
     * 
318
     * @return 
319
     */
320
    public function safeFilters()
321
    {
322
        $filters = [];
323
324
        foreach ($this->filters() as $filterName => $query) {
325
            $filters[str_slug($filterName)] = $filterName;
326
        }
327
328
        return $filters;
329
    }
330
331
    /**
332
     * Set the Query Filter.
333
     * 
334
     * @param array $filter
335
     */
336
    public function setQueryFilter($filter = [])
337
    {
338
        $this->queryFilter = $filter;
339
    }
340
}
341