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

Test Failed
Push — master ( 84126c...7850e4 )
by Cristian
02:36 queued 15s
created

Read::abortIfInvalidPageLength()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 2
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 4
rs 10
1
<?php
2
3
namespace Backpack\CRUD\app\Library\CrudPanel\Traits;
4
5
/**
6
 * Properties and methods used by the List operation.
7
 */
8
trait Read
9
{
10
    /**
11
     * Find and retrieve the id of the current entry.
12
     *
13
     * @return int|bool The id in the db or false.
14
     */
15
    public function getCurrentEntryId()
16
    {
17
        if ($this->entry) {
18
            return $this->entry->getKey();
19
        }
20
21
        $params = \Route::current()->parameters();
22
23
        return  // use the entity name to get the current entry
24
                // this makes sure the ID is corrent even for nested resources
25
                $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

25
                $this->/** @scrutinizer ignore-call */ 
26
                       getRequest()->input($this->entity_name) ??
Loading history...
26
                // otherwise use the next to last parameter
27
                array_values($params)[count($params) - 1] ??
28
                // otherwise return false
29
                false;
30
    }
31
32
    /**
33
     * Find and retrieve the current entry.
34
     *
35
     * @return \Illuminate\Database\Eloquent\Model|bool The row in the db or false.
36
     */
37
    public function getCurrentEntry()
38
    {
39
        $id = $this->getCurrentEntryId();
40
41
        if (! $id) {
42
            return false;
43
        }
44
45
        return $this->getEntry($id);
46
    }
47
48
    /**
49
     * Find and retrieve an entry in the database or fail.
50
     *
51
     * @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...
52
     *
53
     * @return \Illuminate\Database\Eloquent\Model The row in the db.
54
     */
55
    public function getEntry($id)
56
    {
57
        if (! $this->entry) {
58
            $this->entry = $this->model->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...
59
            $this->entry = $this->entry->withFakes();
60
        }
61
62
        return $this->entry;
63
    }
64
65
    /**
66
     * Find and retrieve an entry in the database or fail.
67
     *
68
     * @param int The id of the row in the db to fetch.
69
     *
70
     * @return \Illuminate\Database\Eloquent\Model The row in the db.
71
     */
72
    public function getEntryWithoutFakes($id)
73
    {
74
        return $this->model->findOrFail($id);
75
    }
76
77
    /**
78
     * Make the query JOIN all relationships used in the columns, too,
79
     * so there will be less database queries overall.
80
     */
81
    public function autoEagerLoadRelationshipColumns()
82
    {
83
        $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

83
        /** @scrutinizer ignore-call */ 
84
        $relationships = $this->getColumnsRelationships();
Loading history...
84
85
        if (count($relationships)) {
86
            $this->with($relationships);
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

86
            $this->/** @scrutinizer ignore-call */ 
87
                   with($relationships);
Loading history...
87
        }
88
    }
89
90
    /**
91
     * Get all entries from the database.
92
     *
93
     * @return array|\Illuminate\Database\Eloquent\Collection
94
     */
95
    public function getEntries()
96
    {
97
        $this->autoEagerLoadRelationshipColumns();
98
99
        $entries = $this->query->get();
100
101
        // add the fake columns for each entry
102
        foreach ($entries as $key => $entry) {
103
            $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

103
            $entry->addFakes($this->/** @scrutinizer ignore-call */ getFakeColumnsAsArray());
Loading history...
104
        }
105
106
        return $entries;
107
    }
108
109
    /**
110
     * Enable the DETAILS ROW functionality:.
111
     *
112
     * In the table view, show a plus sign next to each entry.
113
     * 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.
114
     */
115
    public function enableDetailsRow()
116
    {
117
        $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

117
        $this->/** @scrutinizer ignore-call */ 
118
               setOperationSetting('detailsRow', true);
Loading history...
118
    }
119
120
    /**
121
     * Disable the DETAILS ROW functionality:.
122
     */
123
    public function disableDetailsRow()
124
    {
125
        $this->setOperationSetting('detailsRow', false);
126
    }
127
128
    /**
129
     * Add two more columns at the beginning of the ListEntrie table:
130
     * - one shows the checkboxes needed for bulk actions
131
     * - one is blank, in order for evenual detailsRow or expand buttons
132
     * to be in a separate column.
133
     */
134
    public function enableBulkActions()
135
    {
136
        if ($this->getOperationSetting('bulkActions') == true) {
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

136
        if ($this->/** @scrutinizer ignore-call */ getOperationSetting('bulkActions') == true) {
Loading history...
137
            return;
138
        }
139
140
        $this->setOperationSetting('bulkActions', true);
141
142
        $this->addColumn([
0 ignored issues
show
Bug introduced by
It seems like addColumn() 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

142
        $this->/** @scrutinizer ignore-call */ 
143
               addColumn([
Loading history...
143
            'type'            => 'checkbox',
144
            'name'            => 'bulk_actions',
145
            'label'           => ' <input type="checkbox" class="crud_bulk_actions_main_checkbox" style="width: 16px; height: 16px;" />',
146
            'priority'        => 0,
147
            'searchLogic'     => false,
148
            'orderable'       => false,
149
            'visibleInTable'  => true,
150
            'visibleInModal'  => false,
151
            'visibleInExport' => false,
152
            'visibleInShow'   => false,
153
            'hasActions'      => true,
154
        ])->makeFirstColumn();
155
156
        $this->addColumn([
157
            'type'            => 'custom_html',
158
            'name'            => 'blank_first_column',
159
            'label'           => ' ',
160
            'priority'        => 0,
161
            'searchLogic'     => false,
162
            'orderable'       => false,
163
            'visibleInTabel'  => true,
164
            'visibleInModal'  => false,
165
            'visibleInExport' => false,
166
            'visibleInShow'   => false,
167
            'hasActions'      => true,
168
        ])->makeFirstColumn();
169
    }
170
171
    /**
172
     * Remove the two columns needed for bulk actions.
173
     */
174
    public function disableBulkActions()
175
    {
176
        $this->setOperationSetting('bulkActions', false);
177
178
        $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

178
        $this->/** @scrutinizer ignore-call */ 
179
               removeColumn('bulk_actions');
Loading history...
179
        $this->removeColumn('blank_first_column');
180
    }
181
182
    /**
183
     * Set the number of rows that should be show on the list view.
184
     */
185
    public function setDefaultPageLength($value)
186
    {
187
        $this->abortIfInvalidPageLength($value);
188
189
        $this->setOperationSetting('defaultPageLength', $value);
190
    }
191
192
    /**
193
     * Get the number of rows that should be show on the list view.
194
     *
195
     * @return int
196
     */
197
    public function getDefaultPageLength()
198
    {
199
        return $this->getOperationSetting('defaultPageLength') ?? config('backpack.crud.operations.list.defaultPageLength') ?? 25;
200
    }
201
202
    /**
203
     * If a custom page length was specified as default, make sure it
204
     * also show up in the page length menu.
205
     */
206
    public function addCustomPageLengthToPageLengthMenu()
207
    {
208
        $values = $this->getOperationSetting('pageLengthMenu')[0];
209
        $labels = $this->getOperationSetting('pageLengthMenu')[1];
210
211
        if (array_search($this->getDefaultPageLength(), $values) === false) {
212
            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...
213
                if ($values[$i] > $this->getDefaultPageLength() || $values[$i] === -1) {
214
                    array_splice($values, $i, 0, $this->getDefaultPageLength());
215
                    array_splice($labels, $i, 0, $this->getDefaultPageLength());
216
                    break;
217
                }
218
                if ($i === count($values) - 1) {
219
                    $values[] = $this->getDefaultPageLength();
220
                    $labels[] = $this->getDefaultPageLength();
221
                    break;
222
                }
223
            }
224
        }
225
226
        $this->setOperationSetting('pageLengthMenu', [$values, $labels]);
227
    }
228
229
    /**
230
     * Specify array of available page lengths on the list view.
231
     *
232
     * @param array|int $menu
233
     *
234
     * https://backpackforlaravel.com/docs/4.1/crud-cheat-sheet#page-length
235
     */
236
    public function setPageLengthMenu($menu)
237
    {
238
        if (is_array($menu)) {
239
            // start checking $menu integrity
240
            if (count($menu) !== count($menu, COUNT_RECURSIVE)) {
241
                // developer defined as setPageLengthMenu([[50, 100, 300]]) or setPageLengthMenu([[50, 100, 300],['f','h','t']])
242
                // we will apply the same labels as the values to the menu if developer didn't
243
                $this->abortIfInvalidPageLength($menu[0]);
244
245
                if (! isset($menu[1]) || ! is_array($menu[1])) {
246
                    $menu[1] = $menu[0];
247
                }
248
            } else {
249
                // developer defined setPageLengthMenu([10 => 'f', 100 => 'h', 300 => 't']) OR setPageLengthMenu([50, 100, 300])
250
                $menu = $this->buildPageLengthMenuFromArray($menu);
251
            }
252
        } else {
253
            // developer added only a single value setPageLengthMenu(10)
254
            $this->abortIfInvalidPageLength($menu);
255
256
            $menu = [[$menu], [$menu]];
257
        }
258
259
        $this->setOperationSetting('pageLengthMenu', $menu);
260
    }
261
262
    /**
263
     * Builds the menu from the given array. It works out with two different types of arrays:
264
     *  [1, 2, 3] AND [1 => 'one', 2 => 'two', 3 => 'three'].
265
     *
266
     * @param array $menu
267
     * @return array
268
     */
269
    private function buildPageLengthMenuFromArray($menu)
270
    {
271
        // check if the values of the array are strings, in case developer defined:
272
        // setPageLengthMenu([0 => 'f', 100 => 'h', 300 => 't'])
273
        if (count(array_filter(array_values($menu), 'is_string')) > 0) {
274
            $values = array_keys($menu);
275
            $labels = array_values($menu);
276
277
            $this->abortIfInvalidPageLength($values);
278
279
            return [$values, $labels];
280
        } else {
281
            // developer defined length as setPageLengthMenu([50, 100, 300])
282
            // we will use the same values as labels
283
            $this->abortIfInvalidPageLength($menu);
284
285
            return [$menu, $menu];
286
        }
287
    }
288
289
    /**
290
     * Get page length menu for the list view.
291
     *
292
     * @return array
293
     */
294
    public function getPageLengthMenu()
295
    {
296
        // if we have a 2D array, update all the values in the right hand array to their translated values
297
        if (isset($this->getOperationSetting('pageLengthMenu')[1]) && is_array($this->getOperationSetting('pageLengthMenu')[1])) {
298
            $aux = $this->getOperationSetting('pageLengthMenu');
299
            foreach ($this->getOperationSetting('pageLengthMenu')[1] as $key => $val) {
300
                $aux[1][$key] = trans($val);
301
            }
302
            $this->setOperationSetting('pageLengthMenu', $aux);
303
        }
304
        $this->addCustomPageLengthToPageLengthMenu();
305
306
        return $this->getOperationSetting('pageLengthMenu');
307
    }
308
309
    /**
310
     * Checks if the provided PageLength segment is valid.
311
     *
312
     * @param array|int $value
313
     * @return void
314
     */
315
    private function abortIfInvalidPageLength($value)
316
    {
317
        if ($value === 0 || (is_array($value) && in_array(0, $value))) {
318
            abort(500, 'You should not use 0 as a key in paginator. If you are looking for "ALL" option, use -1 instead.');
319
        }
320
    }
321
322
    /*
323
    |--------------------------------------------------------------------------
324
    |                                EXPORT BUTTONS
325
    |--------------------------------------------------------------------------
326
    */
327
328
    /**
329
     * Tell the list view to show the DataTables export buttons.
330
     */
331
    public function enableExportButtons()
332
    {
333
        $this->setOperationSetting('exportButtons', true);
334
    }
335
336
    /**
337
     * Check if export buttons are enabled for the table view.
338
     *
339
     * @return bool
340
     */
341
    public function exportButtons()
342
    {
343
        return $this->getOperationSetting('exportButtons') ?? false;
344
    }
345
}
346