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
Push — eager-load-relationships-on-up... ( a9f064 )
by Pedro
15:31
created

Read::eagerLoadRelationshipFields()   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 Backpack\CRUD\app\Exceptions\BackpackProRequiredException;
6
use Exception;
7
use Illuminate\Support\Facades\Route;
8
use Illuminate\Support\Collection;
9
use Illuminate\Support\Str;
10
/**
11
 * Properties and methods used by the List operation.
12
 */
13
trait Read
14
{
15
    /**
16
     * Find and retrieve the id of the current entry.
17
     *
18
     * @return int|bool The id in the db or false.
19
     */
20
    public function getCurrentEntryId()
21
    {
22
        if ($this->entry) {
23
            return $this->entry->getKey();
24
        }
25
26
        $params = Route::current()?->parameters() ?? [];
27
28
        return  // use the entity name to get the current entry
29
                // this makes sure the ID is current even for nested resources
30
                $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

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

61
        return $this->/** @scrutinizer ignore-call */ setLocaleOnModel($entry);
Loading history...
62
    }
63
64
    /**
65
     * Find and retrieve an entry in the database or fail.
66
     *
67
     * @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...
68
     * @return \Illuminate\Database\Eloquent\Model The row in the db.
69
     */
70
    public function getEntry($id)
71
    {
72
        if (! $this->entry) {
73
            if($this->getOperationSetting('eagerLoadRelationships')) {
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

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

133
        $this->/** @scrutinizer ignore-call */ 
134
               with($this->getRelationshipsFromCrudObjects('columns'));
Loading history...
134
    }
135
136
    public function eagerLoadRelationshipFields()
137
    {
138
        $this->with($this->getRelationshipsFromCrudObjects('fields'));
139
    }
140
141
    private function getRelationshipsFromCrudObjects(string $crudObjectType): array
142
    {
143
        $crudObjects = $this->{$crudObjectType}();
144
145
        $relationStrings = [];
146
147
        foreach ($crudObjects as $crudObjectName => $attributes) {
148
            $relationString = isset($attributes['entity']) && $attributes['entity'] !== false ? $attributes['entity'] : '';
149
            
150
            if(!$relationString) {
151
                continue;
152
            }
153
154
            if (strpos($attributes['entity'], '.') === false) {
155
                $relationStrings[] = $relationString;
156
            }
157
158
            $relationAttribute = $attributes['attribute'] ?? null;
159
160
161
            if ($relationAttribute) {
162
                $relationString = Str::endsWith($relationString, $relationAttribute) ? Str::beforeLast($relationString, '.') : $relationString;
163
164
                $relationStrings[] = $relationString;
165
166
                continue;
167
            }
168
169
            $parts = explode('.', $relationString);
170
            $model = $this->model;
171
172
            // Iterate over each relation part to find the valid relations without attributes
173
            // We should eager load the relation but not the attribute
174
            foreach ($parts as $i => $part) {
175
                try {
176
                    $model = $model->$part()->getRelated();
177
                } catch (Exception $e) {
178
                    $relationString = implode('.', array_slice($parts, 0, $i));
179
                }
180
            }
181
182
            $relationStrings[] = $relationString;
183
184
            continue;
185
        }
186
187
        return array_unique($relationStrings);
188
    }
189
190
    /**
191
     * Get all entries from the database.
192
     *
193
     * @return array|\Illuminate\Database\Eloquent\Collection
194
     */
195
    public function getEntries()
196
    {
197
        $this->autoEagerLoadRelationshipColumns();
198
199
        $entries = $this->query->get();
200
201
        // add the fake columns for each entry
202
        foreach ($entries as $key => $entry) {
203
            $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

203
            $entry->addFakes($this->/** @scrutinizer ignore-call */ getFakeColumnsAsArray());
Loading history...
204
        }
205
206
        return $entries;
207
    }
208
209
    /**
210
     * Enable the DETAILS ROW functionality:.
211
     *
212
     * In the table view, show a plus sign next to each entry.
213
     * 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.
214
     */
215
    public function enableDetailsRow()
216
    {
217
        if (! backpack_pro()) {
218
            throw new BackpackProRequiredException('Details row');
219
        }
220
221
        $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

221
        $this->/** @scrutinizer ignore-call */ 
222
               setOperationSetting('detailsRow', true);
Loading history...
222
    }
223
224
    /**
225
     * Disable the DETAILS ROW functionality:.
226
     */
227
    public function disableDetailsRow()
228
    {
229
        $this->setOperationSetting('detailsRow', false);
230
    }
231
232
    /**
233
     * Add two more columns at the beginning of the ListEntries table:
234
     * - one shows the checkboxes needed for bulk actions
235
     * - one is blank, in order for evenual detailsRow or expand buttons
236
     * to be in a separate column.
237
     */
238
    public function enableBulkActions()
239
    {
240
        $this->setOperationSetting('bulkActions', true);
241
    }
242
243
    /**
244
     * Remove the two columns needed for bulk actions.
245
     */
246
    public function disableBulkActions()
247
    {
248
        $this->setOperationSetting('bulkActions', false);
249
250
        $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

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