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 — master (#3558)
by
unknown
14:53
created

Read::exportButtons()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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

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

85
        /** @scrutinizer ignore-call */ 
86
        $relationships = $this->getColumnsRelationships();
Loading history...
86
87
        foreach ($relationships as $relation) {
88
            if (strpos($relation, '.') !== false) {
89
                $relation_parts = explode('.', $relation);
90
                $last_relation_part = array_pop($relation_parts);
91
92
                $last_valid_relation_method = array_reduce(array_splice($relation_parts, 0, count($relation_parts)), function ($obj, $method) {
93
                    try {
94
                        $result = $obj->$method();
95
96
                        return $result->getRelated();
97
                    } catch (Exception $e) {
98
                        return $method;
99
                    }
100
                }, $this->model);
101
102
                // when this keys don't match means the last part of the relation string is the attribute in the relation and
103
                // not a nested relation. In that case, we should eager load the relation but not the attribute
104
                if ($last_valid_relation_method != $last_relation_part) {
105
                    // remove the last part of the relation string because it is the attribute in the relationship
106
                    $relation = substr($relation, 0, strrpos($relation, '.'));
107
                }
108
            }
109
            $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

109
            $this->/** @scrutinizer ignore-call */ 
110
                   with($relation);
Loading history...
110
        }
111
    }
112
113
    /**
114
     * Get all entries from the database.
115
     *
116
     * @return array|\Illuminate\Database\Eloquent\Collection
117
     */
118
    public function getEntries()
119
    {
120
        $this->autoEagerLoadRelationshipColumns();
121
122
        $entries = $this->query->get();
123
124
        // add the fake columns for each entry
125
        foreach ($entries as $key => $entry) {
126
            $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

126
            $entry->addFakes($this->/** @scrutinizer ignore-call */ getFakeColumnsAsArray());
Loading history...
127
        }
128
129
        return $entries;
130
    }
131
132
    /**
133
     * Enable the DETAILS ROW functionality:.
134
     *
135
     * In the table view, show a plus sign next to each entry.
136
     * 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.
137
     */
138
    public function enableDetailsRow()
139
    {
140
        $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

140
        $this->/** @scrutinizer ignore-call */ 
141
               setOperationSetting('detailsRow', true);
Loading history...
141
    }
142
143
    /**
144
     * Disable the DETAILS ROW functionality:.
145
     */
146
    public function disableDetailsRow()
147
    {
148
        $this->setOperationSetting('detailsRow', false);
149
    }
150
151
    /**
152
     * Add two more columns at the beginning of the ListEntrie table:
153
     * - one shows the checkboxes needed for bulk actions
154
     * - one is blank, in order for evenual detailsRow or expand buttons
155
     * to be in a separate column.
156
     */
157
    public function enableBulkActions()
158
    {
159
        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

159
        if ($this->/** @scrutinizer ignore-call */ getOperationSetting('bulkActions') == true) {
Loading history...
160
            return;
161
        }
162
163
        $this->setOperationSetting('bulkActions', true);
164
165
        $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

165
        $this->/** @scrutinizer ignore-call */ 
166
               addColumn([
Loading history...
166
            'type'            => 'checkbox',
167
            'name'            => 'bulk_actions',
168
            'label'           => ' <input type="checkbox" class="crud_bulk_actions_main_checkbox" style="width: 16px; height: 16px;" />',
169
            'priority'        => 0,
170
            'searchLogic'     => false,
171
            'orderable'       => false,
172
            'visibleInTable'  => true,
173
            'visibleInModal'  => false,
174
            'visibleInExport' => false,
175
            'visibleInShow'   => false,
176
            'hasActions'      => true,
177
        ])->makeFirstColumn();
178
179
        $this->addColumn([
180
            'type'            => 'custom_html',
181
            'name'            => 'blank_first_column',
182
            'label'           => ' ',
183
            'priority'        => 0,
184
            'searchLogic'     => false,
185
            'orderable'       => false,
186
            'visibleInTabel'  => true,
187
            'visibleInModal'  => false,
188
            'visibleInExport' => false,
189
            'visibleInShow'   => false,
190
            'hasActions'      => true,
191
        ])->makeFirstColumn();
192
    }
193
194
    /**
195
     * Remove the two columns needed for bulk actions.
196
     */
197
    public function disableBulkActions()
198
    {
199
        $this->setOperationSetting('bulkActions', false);
200
201
        $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

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