Scrutinizer GitHub App not installed

We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.

Install GitHub App

Passed
Pull Request — main (#5503)
by Pedro
37:11 queued 22:22
created

Read   B

Complexity

Total Complexity 52

Size/Duplication

Total Lines 373
Duplicated Lines 0 %

Importance

Changes 2
Bugs 1 Features 1
Metric Value
eloc 102
c 2
b 1
f 1
dl 0
loc 373
rs 7.44
wmc 52

22 Methods

Rating   Name   Duplication   Size   Complexity  
A getEntry() 0 8 2
A getEntryWithoutFakes() 0 3 1
A enableBulkActions() 0 3 1
A disableDetailsRow() 0 3 1
A disableBulkActions() 0 5 1
A getDefaultPageLength() 0 3 1
A getModelWithCrudPanelQuery() 0 3 1
A autoEagerLoadRelationshipColumns() 0 20 5
A getCurrentEntry() 0 9 2
A getCurrentEntryId() 0 15 2
A getEntries() 0 12 2
A getEntryWithLocale() 0 14 4
A setDefaultPageLength() 0 5 1
A enableDetailsRow() 0 7 2
A setPageLengthMenu() 0 24 5
A addCustomPageLengthToPageLengthMenu() 0 21 6
A enableExportButtons() 0 9 2
A buildPageLengthMenuFromArray() 0 17 2
A getPageLengthMenu() 0 13 4
A exportButtons() 0 3 1
A abortIfInvalidPageLength() 0 4 4
A maxPageLength() 0 9 2

How to fix   Complexity   

Complex Class

Complex classes like Read often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Read, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Backpack\CRUD\app\Library\CrudPanel\Traits;
4
5
use Backpack\CRUD\app\Exceptions\BackpackProRequiredException;
6
use Exception;
7
8
/**
9
 * Properties and methods used by the List operation.
10
 */
11
trait Read
12
{
13
    /**
14
     * Find and retrieve the id of the current entry.
15
     *
16
     * @return int|bool The id in the db or false.
17
     */
18
    public function getCurrentEntryId()
19
    {
20
        if ($this->entry) {
21
            return $this->entry->getKey();
22
        }
23
24
        $params = \Route::current()->parameters();
25
26
        return  // use the entity name to get the current entry
27
                // this makes sure the ID is corrent even for nested resources
28
                $this->getRequest()->input($this->entity_name) ??
0 ignored issues
show
Bug introduced by
It seems like getRequest() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

28
                $this->/** @scrutinizer ignore-call */ 
29
                       getRequest()->input($this->entity_name) ??
Loading history...
29
                // otherwise use the next to last parameter
30
                array_values($params)[count($params) - 1] ??
31
                // otherwise return false
32
                false;
33
    }
34
35
    /**
36
     * Find and retrieve the current entry.
37
     *
38
     * @return \Illuminate\Database\Eloquent\Model|bool The row in the db or false.
39
     */
40
    public function getCurrentEntry()
41
    {
42
        $id = $this->getCurrentEntryId();
43
44
        if ($id === false) {
45
            return false;
46
        }
47
48
        return $this->getEntry($id);
49
    }
50
51
    /**
52
     * Find and retrieve an entry in the database or fail.
53
     *
54
     * @param int The id of the row in the db to fetch.
0 ignored issues
show
Bug introduced by
The type Backpack\CRUD\app\Library\CrudPanel\Traits\The was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
55
     * @return \Illuminate\Database\Eloquent\Model The row in the db.
56
     */
57
    public function getEntry($id)
58
    {
59
        if (! $this->entry) {
60
            $this->entry = $this->getModelWithCrudPanelQuery()->findOrFail($id);
0 ignored issues
show
Bug Best Practice introduced by
The property entry does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
61
            $this->entry = $this->entry->withFakes();
62
        }
63
64
        return $this->entry;
65
    }
66
67
    /**
68
     * Find and retrieve an entry in the database or fail.
69
     * When found, make sure we set the Locale on it.
70
     *
71
     * @param int The id of the row in the db to fetch.
72
     * @return \Illuminate\Database\Eloquent\Model The row in the db.
73
     */
74
    public function getEntryWithLocale($id)
75
    {
76
        if (! $this->entry) {
77
            $this->entry = $this->getEntry($id);
0 ignored issues
show
Bug Best Practice introduced by
The property entry does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
78
        }
79
80
        if ($this->entry->translationEnabled()) {
81
            $locale = request('_locale', \App::getLocale());
82
            if (in_array($locale, array_keys($this->entry->getAvailableLocales()))) {
83
                $this->entry->setLocale($locale);
84
            }
85
        }
86
87
        return $this->entry;
88
    }
89
90
    /**
91
     * Return a Model builder instance with the current crud query applied.
92
     *
93
     * @return \Illuminate\Database\Eloquent\Builder
94
     */
95
    public function getModelWithCrudPanelQuery()
96
    {
97
        return $this->model->setQuery($this->query->getQuery());
98
    }
99
100
    /**
101
     * Find and retrieve an entry in the database or fail.
102
     *
103
     * @param int The id of the row in the db to fetch.
104
     * @return \Illuminate\Database\Eloquent\Model The row in the db.
105
     */
106
    public function getEntryWithoutFakes($id)
107
    {
108
        return $this->getModelWithCrudPanelQuery()->findOrFail($id);
109
    }
110
111
    /**
112
     * Make the query JOIN all relationships used in the columns, too,
113
     * so there will be less database queries overall.
114
     */
115
    public function autoEagerLoadRelationshipColumns()
116
    {
117
        $relationships = $this->getColumnsRelationships();
0 ignored issues
show
Bug introduced by
It seems like getColumnsRelationships() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

117
        /** @scrutinizer ignore-call */ 
118
        $relationships = $this->getColumnsRelationships();
Loading history...
118
119
        foreach ($relationships as $relation) {
120
            if (strpos($relation, '.') !== false) {
121
                $parts = explode('.', $relation);
122
                $model = $this->model;
123
124
                // Iterate over each relation part to find the valid relations without attributes
125
                // We should eager load the relation but not the attribute
126
                foreach ($parts as $i => $part) {
127
                    try {
128
                        $model = $model->$part()->getRelated();
129
                    } catch (Exception $e) {
130
                        $relation = join('.', array_slice($parts, 0, $i));
131
                    }
132
                }
133
            }
134
            $this->with($relation);
0 ignored issues
show
Bug introduced by
It seems like with() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

134
            $this->/** @scrutinizer ignore-call */ 
135
                   with($relation);
Loading history...
135
        }
136
    }
137
138
    /**
139
     * Get all entries from the database.
140
     *
141
     * @return array|\Illuminate\Database\Eloquent\Collection
142
     */
143
    public function getEntries()
144
    {
145
        $this->autoEagerLoadRelationshipColumns();
146
147
        $entries = $this->query->get();
148
149
        // add the fake columns for each entry
150
        foreach ($entries as $key => $entry) {
151
            $entry->addFakes($this->getFakeColumnsAsArray());
0 ignored issues
show
Bug introduced by
It seems like getFakeColumnsAsArray() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

151
            $entry->addFakes($this->/** @scrutinizer ignore-call */ getFakeColumnsAsArray());
Loading history...
152
        }
153
154
        return $entries;
155
    }
156
157
    /**
158
     * Enable the DETAILS ROW functionality:.
159
     *
160
     * In the table view, show a plus sign next to each entry.
161
     * When clicking that plus sign, an AJAX call will bring whatever content you want from the EntityCrudController::showDetailsRow($id) and show it to the user.
162
     */
163
    public function enableDetailsRow()
164
    {
165
        if (! backpack_pro()) {
166
            throw new BackpackProRequiredException('Details row');
167
        }
168
169
        $this->setOperationSetting('detailsRow', true);
0 ignored issues
show
Bug introduced by
It seems like setOperationSetting() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

169
        $this->/** @scrutinizer ignore-call */ 
170
               setOperationSetting('detailsRow', true);
Loading history...
170
    }
171
172
    /**
173
     * Disable the DETAILS ROW functionality:.
174
     */
175
    public function disableDetailsRow()
176
    {
177
        $this->setOperationSetting('detailsRow', false);
178
    }
179
180
    /**
181
     * Add two more columns at the beginning of the ListEntrie table:
182
     * - one shows the checkboxes needed for bulk actions
183
     * - one is blank, in order for evenual detailsRow or expand buttons
184
     * to be in a separate column.
185
     */
186
    public function enableBulkActions()
187
    {
188
        $this->setOperationSetting('bulkActions', true);
189
    }
190
191
    /**
192
     * Remove the two columns needed for bulk actions.
193
     */
194
    public function disableBulkActions()
195
    {
196
        $this->setOperationSetting('bulkActions', false);
197
198
        $this->removeColumn('bulk_actions');
0 ignored issues
show
Bug introduced by
It seems like removeColumn() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

198
        $this->/** @scrutinizer ignore-call */ 
199
               removeColumn('bulk_actions');
Loading history...
199
    }
200
201
    /**
202
     * Set the number of rows that should be show on the list view.
203
     */
204
    public function setDefaultPageLength($value)
205
    {
206
        $this->abortIfInvalidPageLength($value);
207
208
        $this->setOperationSetting('defaultPageLength', $value);
209
    }
210
211
    /**
212
     * Get the number of rows that should be show on the list view.
213
     *
214
     * @return int
215
     */
216
    public function getDefaultPageLength()
217
    {
218
        return $this->getOperationSetting('defaultPageLength') ?? config('backpack.crud.operations.list.defaultPageLength') ?? 25;
0 ignored issues
show
Bug introduced by
It seems like getOperationSetting() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

218
        return $this->/** @scrutinizer ignore-call */ getOperationSetting('defaultPageLength') ?? config('backpack.crud.operations.list.defaultPageLength') ?? 25;
Loading history...
219
    }
220
221
    /**
222
     * Get the higher limit from the page length menu.
223
     * -1 means "All" so if present it means no limit.
224
     */
225
    public function maxPageLength(): int
226
    {
227
        $pageLengthMenu = $this->getPageLengthMenu();
228
229
        if (in_array(-1, $pageLengthMenu[0])) {
230
            return -1;
231
        }
232
233
        return (int) max($pageLengthMenu[0]);
234
    }
235
236
    /**
237
     * If a custom page length was specified as default, make sure it
238
     * also show up in the page length menu.
239
     */
240
    public function addCustomPageLengthToPageLengthMenu()
241
    {
242
        $values = $this->getOperationSetting('pageLengthMenu')[0];
243
        $labels = $this->getOperationSetting('pageLengthMenu')[1];
244
245
        if (array_search($this->getDefaultPageLength(), $values) === false) {
246
            for ($i = 0; $i < count($values); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
247
                if ($values[$i] > $this->getDefaultPageLength() || $values[$i] === -1) {
248
                    array_splice($values, $i, 0, $this->getDefaultPageLength());
249
                    array_splice($labels, $i, 0, $this->getDefaultPageLength());
250
                    break;
251
                }
252
                if ($i === count($values) - 1) {
253
                    $values[] = $this->getDefaultPageLength();
254
                    $labels[] = $this->getDefaultPageLength();
255
                    break;
256
                }
257
            }
258
        }
259
260
        $this->setOperationSetting('pageLengthMenu', [$values, $labels]);
261
    }
262
263
    /**
264
     * Specify array of available page lengths on the list view.
265
     *
266
     * @param  array|int  $menu
267
     *
268
     * https://backpackforlaravel.com/docs/4.1/crud-cheat-sheet#page-length
269
     */
270
    public function setPageLengthMenu($menu)
271
    {
272
        if (is_array($menu)) {
273
            // start checking $menu integrity
274
            if (count($menu) !== count($menu, COUNT_RECURSIVE)) {
275
                // developer defined as setPageLengthMenu([[50, 100, 300]]) or setPageLengthMenu([[50, 100, 300],['f','h','t']])
276
                // we will apply the same labels as the values to the menu if developer didn't
277
                $this->abortIfInvalidPageLength($menu[0]);
278
279
                if (! isset($menu[1]) || ! is_array($menu[1])) {
280
                    $menu[1] = $menu[0];
281
                }
282
            } else {
283
                // developer defined setPageLengthMenu([10 => 'f', 100 => 'h', 300 => 't']) OR setPageLengthMenu([50, 100, 300])
284
                $menu = $this->buildPageLengthMenuFromArray($menu);
285
            }
286
        } else {
287
            // developer added only a single value setPageLengthMenu(10)
288
            $this->abortIfInvalidPageLength($menu);
289
290
            $menu = [[$menu], [$menu]];
291
        }
292
293
        $this->setOperationSetting('pageLengthMenu', $menu);
294
    }
295
296
    /**
297
     * Builds the menu from the given array. It works out with two different types of arrays:
298
     *  [1, 2, 3] AND [1 => 'one', 2 => 'two', 3 => 'three'].
299
     *
300
     * @param  array  $menu
301
     * @return array
302
     */
303
    private function buildPageLengthMenuFromArray($menu)
304
    {
305
        // check if the values of the array are strings, in case developer defined:
306
        // setPageLengthMenu([0 => 'f', 100 => 'h', 300 => 't'])
307
        if (count(array_filter(array_values($menu), 'is_string')) > 0) {
308
            $values = array_keys($menu);
309
            $labels = array_values($menu);
310
311
            $this->abortIfInvalidPageLength($values);
312
313
            return [$values, $labels];
314
        } else {
315
            // developer defined length as setPageLengthMenu([50, 100, 300])
316
            // we will use the same values as labels
317
            $this->abortIfInvalidPageLength($menu);
318
319
            return [$menu, $menu];
320
        }
321
    }
322
323
    /**
324
     * Get page length menu for the list view.
325
     *
326
     * @return array
327
     */
328
    public function getPageLengthMenu()
329
    {
330
        // if we have a 2D array, update all the values in the right hand array to their translated values
331
        if (isset($this->getOperationSetting('pageLengthMenu')[1]) && is_array($this->getOperationSetting('pageLengthMenu')[1])) {
332
            $aux = $this->getOperationSetting('pageLengthMenu');
333
            foreach ($this->getOperationSetting('pageLengthMenu')[1] as $key => $val) {
334
                $aux[1][$key] = trans($val);
335
            }
336
            $this->setOperationSetting('pageLengthMenu', $aux);
337
        }
338
        $this->addCustomPageLengthToPageLengthMenu();
339
340
        return $this->getOperationSetting('pageLengthMenu');
341
    }
342
343
    /**
344
     * Checks if the provided PageLength segment is valid.
345
     *
346
     * @param  array|int  $value
347
     * @return void
348
     */
349
    private function abortIfInvalidPageLength($value)
350
    {
351
        if ($value === 0 || (is_array($value) && in_array(0, $value))) {
352
            abort(500, 'You should not use 0 as a key in paginator. If you are looking for "ALL" option, use -1 instead.');
353
        }
354
    }
355
356
    /*
357
    |--------------------------------------------------------------------------
358
    |                                EXPORT BUTTONS
359
    |--------------------------------------------------------------------------
360
    */
361
362
    /**
363
     * Tell the list view to show the DataTables export buttons.
364
     */
365
    public function enableExportButtons()
366
    {
367
        if (! backpack_pro()) {
368
            throw new BackpackProRequiredException('Export buttons');
369
        }
370
371
        $this->setOperationSetting('exportButtons', true);
372
        $this->setOperationSetting('showTableColumnPicker', true);
373
        $this->setOperationSetting('showExportButton', true);
374
    }
375
376
    /**
377
     * Check if export buttons are enabled for the table view.
378
     *
379
     * @return bool
380
     */
381
    public function exportButtons()
382
    {
383
        return $this->getOperationSetting('exportButtons') ?? false;
384
    }
385
}
386