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 (#4267)
by Cristian
29:11 queued 14:11
created

Read::shouldUseFallbackLocale()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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

29
                $this->/** @scrutinizer ignore-call */ 
30
                       getRequest()->input($this->entity_name) ??
Loading history...
30
                // otherwise use the next to last parameter
31
                array_values($params)[count($params) - 1] ??
32
                // otherwise return false
33
                false;
34
    }
35
36
    /**
37
     * Find and retrieve the current entry.
38
     *
39
     * @return \Illuminate\Database\Eloquent\Model|bool The row in the db or false.
40
     */
41
    public function getCurrentEntry()
42
    {
43
        $id = $this->getCurrentEntryId();
44
45
        if ($id === false) {
46
            return false;
47
        }
48
49
        return $this->getEntry($id);
50
    }
51
52
    public function getCurrentEntryWithLocale()
53
    {
54
        $entry = $this->getCurrentEntry();
55
56
        if (! $entry) {
57
            return false;
58
        }
59
60
        return $this->setLocaleOnModel($entry);
0 ignored issues
show
Bug introduced by
It seems like setLocaleOnModel() 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

60
        return $this->/** @scrutinizer ignore-call */ setLocaleOnModel($entry);
Loading history...
61
    }
62
63
    /**
64
     * Find and retrieve an entry in the database or fail.
65
     *
66
     * @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...
67
     * @return \Illuminate\Database\Eloquent\Model The row in the db.
68
     */
69
    public function getEntry($id)
70
    {
71
        if (! $this->entry) {
72
            $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...
73
            $this->entry = $this->entry->withFakes();
74
        }
75
76
        return $this->entry;
77
    }
78
79
    private function shouldUseFallbackLocale(): bool|string
80
    {
81
        $fallbackRequestValue = $this->getRequest()->get('_fallback_locale');
82
83
        return $fallbackRequestValue === 'true' ? true : (in_array($fallbackRequestValue, array_keys(config('backpack.crud.locales'))) ? $fallbackRequestValue : false);
84
    }
85
86
    /**
87
     * Find and retrieve an entry in the database or fail.
88
     * When found, make sure we set the Locale on it.
89
     *
90
     * @param int The id of the row in the db to fetch.
91
     * @return \Illuminate\Database\Eloquent\Model The row in the db.
92
     */
93
    public function getEntryWithLocale($id)
94
    {
95
        if (! $this->entry) {
96
            $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...
97
        }
98
99
        return $this->setLocaleOnModel($this->entry);
100
    }
101
102
    /**
103
     * Return a Model builder instance with the current crud query applied.
104
     *
105
     * @return \Illuminate\Database\Eloquent\Builder
106
     */
107
    public function getModelWithCrudPanelQuery()
108
    {
109
        return $this->model->setQuery($this->query->getQuery());
110
    }
111
112
    /**
113
     * Find and retrieve an entry in the database or fail.
114
     *
115
     * @param int The id of the row in the db to fetch.
116
     * @return \Illuminate\Database\Eloquent\Model The row in the db.
117
     */
118
    public function getEntryWithoutFakes($id)
119
    {
120
        return $this->getModelWithCrudPanelQuery()->findOrFail($id);
121
    }
122
123
    /**
124
     * Make the query JOIN all relationships used in the columns, too,
125
     * so there will be less database queries overall.
126
     */
127
    public function autoEagerLoadRelationshipColumns()
128
    {
129
        $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

129
        /** @scrutinizer ignore-call */ 
130
        $relationships = $this->getColumnsRelationships();
Loading history...
130
131
        foreach ($relationships as $relation) {
132
            if (strpos($relation, '.') !== false) {
133
                $parts = explode('.', $relation);
134
                $model = $this->model;
135
136
                // Iterate over each relation part to find the valid relations without attributes
137
                // We should eager load the relation but not the attribute
138
                foreach ($parts as $i => $part) {
139
                    try {
140
                        $model = $model->$part()->getRelated();
141
                    } catch (Exception $e) {
142
                        $relation = implode('.', array_slice($parts, 0, $i));
143
                    }
144
                }
145
            }
146
            $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

146
            $this->/** @scrutinizer ignore-call */ 
147
                   with($relation);
Loading history...
147
        }
148
    }
149
150
    /**
151
     * Get all entries from the database.
152
     *
153
     * @return array|\Illuminate\Database\Eloquent\Collection
154
     */
155
    public function getEntries()
156
    {
157
        $this->autoEagerLoadRelationshipColumns();
158
159
        $entries = $this->query->get();
160
161
        // add the fake columns for each entry
162
        foreach ($entries as $key => $entry) {
163
            $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

163
            $entry->addFakes($this->/** @scrutinizer ignore-call */ getFakeColumnsAsArray());
Loading history...
164
        }
165
166
        return $entries;
167
    }
168
169
    /**
170
     * Enable the DETAILS ROW functionality:.
171
     *
172
     * In the table view, show a plus sign next to each entry.
173
     * 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.
174
     */
175
    public function enableDetailsRow()
176
    {
177
        if (! backpack_pro()) {
178
            throw new BackpackProRequiredException('Details row');
179
        }
180
181
        $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

181
        $this->/** @scrutinizer ignore-call */ 
182
               setOperationSetting('detailsRow', true);
Loading history...
182
    }
183
184
    /**
185
     * Disable the DETAILS ROW functionality:.
186
     */
187
    public function disableDetailsRow()
188
    {
189
        $this->setOperationSetting('detailsRow', false);
190
    }
191
192
    /**
193
     * Add two more columns at the beginning of the ListEntries table:
194
     * - one shows the checkboxes needed for bulk actions
195
     * - one is blank, in order for evenual detailsRow or expand buttons
196
     * to be in a separate column.
197
     */
198
    public function enableBulkActions()
199
    {
200
        $this->setOperationSetting('bulkActions', true);
201
    }
202
203
    /**
204
     * Remove the two columns needed for bulk actions.
205
     */
206
    public function disableBulkActions()
207
    {
208
        $this->setOperationSetting('bulkActions', false);
209
210
        $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

210
        $this->/** @scrutinizer ignore-call */ 
211
               removeColumn('bulk_actions');
Loading history...
211
    }
212
213
    /**
214
     * Set the number of rows that should be show on the list view.
215
     */
216
    public function setDefaultPageLength($value)
217
    {
218
        $this->abortIfInvalidPageLength($value);
219
220
        $this->setOperationSetting('defaultPageLength', $value);
221
    }
222
223
    /**
224
     * Get the number of rows that should be show on the list view.
225
     *
226
     * @return int
227
     */
228
    public function getDefaultPageLength()
229
    {
230
        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

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