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 (#4988)
by Cristian
27:11 queued 12:10
created

Fields::setLoadedFieldTypes()   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 1
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\Library\CrudPanel\CrudField;
6
use Illuminate\Support\Arr;
7
8
trait Fields
9
{
10
    use FieldsProtectedMethods;
11
    use FieldsPrivateMethods;
12
13
    // ------------
14
    // FIELDS
15
    // ------------
16
17
    /**
18
     * Get the CRUD fields for the current operation with name processed to be usable in HTML.
19
     *
20
     * @return array
21
     */
22
    public function fields()
23
    {
24
        return $this->overwriteFieldNamesFromDotNotationToArray($this->getOperationSetting('fields') ?? []);
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

24
        return $this->overwriteFieldNamesFromDotNotationToArray($this->/** @scrutinizer ignore-call */ getOperationSetting('fields') ?? []);
Loading history...
25
    }
26
27
    /**
28
     * Returns the fields as they are stored inside operation setting, not running the
29
     * presentation callbacks like converting the `dot.names` into `dot[names]` for html for example.
30
     */
31
    public function getCleanStateFields()
32
    {
33
        return $this->getOperationSetting('fields') ?? [];
34
    }
35
36
    /**
37
     * The only REALLY MANDATORY attribute when defining a field is the 'name'.
38
     * Everything else Backpack can probably guess. This method makes sure  the
39
     * field definition array is complete, by guessing missing attributes.
40
     *
41
     * @param  string|array  $field  The definition of a field (string or array).
42
     * @return array The correct definition of that field.
43
     */
44
    public function makeSureFieldHasNecessaryAttributes($field)
45
    {
46
        $field = $this->makeSureFieldHasName($field);
47
        $field = $this->makeSureFieldHasEntity($field);
48
        $field = $this->makeSureFieldHasLabel($field);
49
50
        if (isset($field['entity']) && $field['entity'] !== false) {
51
            $field = $this->makeSureFieldHasRelationshipAttributes($field);
52
        }
53
54
        $field = $this->makeSureFieldHasType($field);
55
        $field = $this->makeSureSubfieldsHaveNecessaryAttributes($field);
56
        $field = $this->makeSureMorphSubfieldsAreDefined($field);
0 ignored issues
show
Bug introduced by
The method makeSureMorphSubfieldsAreDefined() does not exist on Backpack\CRUD\app\Library\CrudPanel\Traits\Fields. Did you maybe mean fields()? ( Ignorable by Annotation )

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

56
        /** @scrutinizer ignore-call */ 
57
        $field = $this->makeSureMorphSubfieldsAreDefined($field);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
57
58
        $this->setupFieldValidation($field, $field['parentFieldName'] ?? false);
0 ignored issues
show
Bug introduced by
It seems like setupFieldValidation() 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

58
        $this->/** @scrutinizer ignore-call */ 
59
               setupFieldValidation($field, $field['parentFieldName'] ?? false);
Loading history...
59
60
        return $field;
61
    }
62
63
    /**
64
     * When field is a relationship, Backpack will try to guess some basic attributes from the relation.
65
     *
66
     * @param  array  $field
67
     * @return array
68
     */
69
    public function makeSureFieldHasRelationshipAttributes($field)
70
    {
71
        $field = $this->makeSureFieldHasRelationType($field);
72
        $field = $this->makeSureFieldHasModel($field);
73
        $field = $this->makeSureFieldHasAttribute($field);
74
        $field = $this->makeSureFieldHasMultiple($field);
75
        $field = $this->makeSureFieldHasPivot($field);
76
        $field = $this->makeSureFieldHasType($field);
77
78
        return $field;
79
    }
80
81
    /**
82
     * Register all Eloquent Model events that are defined on fields.
83
     * Eg. saving, saved, creating, created, updating, updated.
84
     *
85
     * @see https://laravel.com/docs/master/eloquent#events
86
     *
87
     * @return void
88
     */
89
    public function registerFieldEvents()
90
    {
91
        foreach ($this->getCleanStateFields() as $key => $field) {
92
            if (isset($field['events'])) {
93
                foreach ($field['events'] as $event => $closure) {
94
                    $this->model->{$event}($closure);
95
                }
96
            }
97
        }
98
    }
99
100
    /**
101
     * Add a field to the create/update form or both.
102
     *
103
     * @param  string|array  $field  The new field.
104
     * @return self
105
     */
106
    public function addField($field)
107
    {
108
        $field = $this->makeSureFieldHasNecessaryAttributes($field);
109
110
        $this->enableTabsIfFieldUsesThem($field);
111
        $this->addFieldToOperationSettings($field);
112
113
        $this->callRegisteredAttributeMacros(new CrudField($field['name']));
0 ignored issues
show
Bug introduced by
It seems like callRegisteredAttributeMacros() 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

113
        $this->/** @scrutinizer ignore-call */ 
114
               callRegisteredAttributeMacros(new CrudField($field['name']));
Loading history...
114
115
        return $this;
116
    }
117
118
    /**
119
     * Add multiple fields to the create/update form or both.
120
     *
121
     * @param  array  $fields  The new fields.
122
     */
123
    public function addFields($fields)
124
    {
125
        if (count($fields)) {
126
            foreach ($fields as $field) {
127
                $this->addField($field);
128
            }
129
        }
130
    }
131
132
    /**
133
     * Move the most recently added field after the given target field.
134
     *
135
     * @param  string  $targetFieldName  The target field name.
136
     */
137
    public function afterField($targetFieldName)
138
    {
139
        $this->transformFields(function ($fields) use ($targetFieldName) {
140
            return $this->moveField($fields, $targetFieldName, false);
141
        });
142
    }
143
144
    /**
145
     * Move the most recently added field before the given target field.
146
     *
147
     * @param  string  $targetFieldName  The target field name.
148
     */
149
    public function beforeField($targetFieldName)
150
    {
151
        $this->transformFields(function ($fields) use ($targetFieldName) {
152
            return $this->moveField($fields, $targetFieldName, true);
153
        });
154
    }
155
156
    /**
157
     * Move this field to be first in the fields list.
158
     *
159
     * @return bool|null
160
     */
161
    public function makeFirstField()
162
    {
163
        if (! $this->fields()) {
164
            return false;
165
        }
166
167
        $firstField = array_keys(array_slice($this->getCleanStateFields(), 0, 1))[0];
168
        $this->beforeField($firstField);
169
    }
170
171
    /**
172
     * Remove a certain field from the create/update/both forms by its name.
173
     *
174
     * @param  string  $name  Field name (as defined with the addField() procedure)
175
     */
176
    public function removeField($name)
177
    {
178
        $this->transformFields(function ($fields) use ($name) {
179
            Arr::forget($fields, $name);
180
181
            return $fields;
182
        });
183
    }
184
185
    /**
186
     * Remove many fields from the create/update/both forms by their name.
187
     *
188
     * @param  array  $array_of_names  A simple array of the names of the fields to be removed.
189
     */
190
    public function removeFields($array_of_names)
191
    {
192
        if (! empty($array_of_names)) {
193
            foreach ($array_of_names as $name) {
194
                $this->removeField($name);
195
            }
196
        }
197
    }
198
199
    /**
200
     * Remove all fields from the create/update/both forms.
201
     */
202
    public function removeAllFields()
203
    {
204
        $current_fields = $this->getCleanStateFields();
205
        if (! empty($current_fields)) {
206
            foreach ($current_fields as $field) {
207
                $this->removeField($field['name']);
208
            }
209
        }
210
    }
211
212
    /**
213
     * Remove an attribute from one field's definition array.
214
     *
215
     * @param  string  $field  The name of the field.
216
     * @param  string  $attribute  The name of the attribute being removed.
217
     */
218
    public function removeFieldAttribute($field, $attribute)
219
    {
220
        $fields = $this->getCleanStateFields();
221
222
        unset($fields[$field][$attribute]);
223
224
        $this->setOperationSetting('fields', $fields);
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

224
        $this->/** @scrutinizer ignore-call */ 
225
               setOperationSetting('fields', $fields);
Loading history...
225
    }
226
227
    /**
228
     * Update value of a given key for a current field.
229
     *
230
     * @param  string  $fieldName  The field name
231
     * @param  array  $modifications  An array of changes to be made.
232
     */
233
    public function modifyField($fieldName, $modifications)
234
    {
235
        $fieldsArray = $this->getCleanStateFields();
236
        $field = $this->firstFieldWhere('name', $fieldName);
237
        $fieldKey = $this->getFieldKey($field);
0 ignored issues
show
Bug introduced by
$field of type boolean is incompatible with the type array expected by parameter $field of Backpack\CRUD\app\Librar...s\Fields::getFieldKey(). ( Ignorable by Annotation )

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

237
        $fieldKey = $this->getFieldKey(/** @scrutinizer ignore-type */ $field);
Loading history...
238
239
        foreach ($modifications as $attributeName => $attributeValue) {
240
            $fieldsArray[$fieldKey][$attributeName] = $attributeValue;
241
        }
242
243
        $this->enableTabsIfFieldUsesThem($modifications);
244
245
        $this->setOperationSetting('fields', $fieldsArray);
246
    }
247
248
    /**
249
     * Set label for a specific field.
250
     *
251
     * @param  string  $field
252
     * @param  string  $label
253
     */
254
    public function setFieldLabel($field, $label)
255
    {
256
        $this->modifyField($field, ['label' => $label]);
257
    }
258
259
    /**
260
     * Check if field is the first of its type in the given fields array.
261
     * It's used in each field_type.blade.php to determine wether to push the css and js content or not (we only need to push the js and css for a field the first time it's loaded in the form, not any subsequent times).
262
     *
263
     * @param  array  $field  The current field being tested if it's the first of its type.
264
     * @return bool true/false
265
     */
266
    public function checkIfFieldIsFirstOfItsType($field)
267
    {
268
        $fields_array = $this->getCleanStateFields();
269
        $first_field = $this->getFirstOfItsTypeInArray($field['type'], $fields_array);
0 ignored issues
show
Bug introduced by
It seems like getFirstOfItsTypeInArray() 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

269
        /** @scrutinizer ignore-call */ 
270
        $first_field = $this->getFirstOfItsTypeInArray($field['type'], $fields_array);
Loading history...
270
271
        if ($first_field && $field['name'] == $first_field['name']) {
272
            return true;
273
        }
274
275
        return false;
276
    }
277
278
    /**
279
     * Decode attributes that are casted as array/object/json in the model.
280
     * So that they are not json_encoded twice before they are stored in the db
281
     * (once by Backpack in front-end, once by Laravel Attribute Casting).
282
     *
283
     * @param  array  $input
284
     * @param  mixed  $model
285
     * @return array
286
     */
287
    public function decodeJsonCastedAttributes($input, $model = false)
288
    {
289
        $model = $model ? $model : $this->model;
290
        $fields = $this->getCleanStateFields();
291
        $casted_attributes = $model->getCastedAttributes();
292
293
        foreach ($fields as $field) {
294
            // Test the field is castable
295
            if (isset($field['name']) && is_string($field['name']) && array_key_exists($field['name'], $casted_attributes)) {
296
                // Handle JSON field types
297
                $jsonCastables = ['array', 'object', 'json'];
298
                $fieldCasting = $casted_attributes[$field['name']];
299
300
                if (in_array($fieldCasting, $jsonCastables) && isset($input[$field['name']]) && ! empty($input[$field['name']]) && ! is_array($input[$field['name']])) {
301
                    try {
302
                        $input[$field['name']] = json_decode($input[$field['name']]);
303
                    } catch (\Exception $e) {
304
                        $input[$field['name']] = [];
305
                    }
306
                }
307
            }
308
        }
309
310
        return $input;
311
    }
312
313
    /**
314
     * @return array
315
     */
316
    public function getCurrentFields()
317
    {
318
        return $this->fields();
319
    }
320
321
    /**
322
     * Order the CRUD fields. If certain fields are missing from the given order array, they will be
323
     * pushed to the new fields array in the original order.
324
     *
325
     * @param  array  $order  An array of field names in the desired order.
326
     */
327
    public function orderFields($order)
328
    {
329
        $this->transformFields(function ($fields) use ($order) {
330
            return $this->applyOrderToFields($fields, $order);
331
        });
332
    }
333
334
    /**
335
     * Get the fields for the create or update forms.
336
     *
337
     * @return array all the fields that need to be shown and their information
338
     */
339
    public function getFields()
340
    {
341
        return $this->fields();
342
    }
343
344
    /**
345
     * Check if the create/update form has upload fields.
346
     * Upload fields are the ones that have "upload" => true defined on them.
347
     *
348
     * @param  string  $form  create/update/both - defaults to 'both'
349
     * @param  bool|int  $id  id of the entity - defaults to false
350
     * @return bool
351
     */
352
    public function hasUploadFields()
353
    {
354
        $fields = $this->getCleanStateFields();
355
        $upload_fields = Arr::where($fields, function ($value, $key) {
356
            // check if any subfields have uploads
357
            if (isset($value['subfields'])) {
358
                foreach ($value['subfields'] as $subfield) {
359
                    if (isset($subfield['upload']) && $subfield['upload'] === true) {
360
                        return true;
361
                    }
362
                }
363
            }
364
365
            return isset($value['upload']) && $value['upload'] == true;
366
        });
367
368
        return count($upload_fields) ? true : false;
369
    }
370
371
    // ----------------------
372
    // FIELD ASSET MANAGEMENT
373
    // ----------------------
374
375
    /**
376
     * Get all the field types whose resources (JS and CSS) have already been loaded on page.
377
     *
378
     * @return array Array with the names of the field types.
379
     */
380
    public function getLoadedFieldTypes()
381
    {
382
        return $this->getOperationSetting('loadedFieldTypes') ?? [];
383
    }
384
385
    /**
386
     * Set an array of field type names as already loaded for the current operation.
387
     *
388
     * @param  array  $fieldTypes
389
     */
390
    public function setLoadedFieldTypes($fieldTypes)
391
    {
392
        $this->setOperationSetting('loadedFieldTypes', $fieldTypes);
393
    }
394
395
    /**
396
     * Get a namespaced version of the field type name.
397
     * Appends the 'view_namespace' attribute of the field to the `type', using dot notation.
398
     *
399
     * @param  mixed  $field
400
     * @return string Namespaced version of the field type name. Ex: 'text', 'custom.view.path.text'
401
     */
402
    public function getFieldTypeWithNamespace($field)
403
    {
404
        if (is_array($field)) {
405
            $fieldType = $field['type'];
406
            if (isset($field['view_namespace'])) {
407
                $fieldType = implode('.', [$field['view_namespace'], $field['type']]);
408
            }
409
        } else {
410
            $fieldType = $field;
411
        }
412
413
        return $fieldType;
414
    }
415
416
    /**
417
     * Add a new field type to the loadedFieldTypes array.
418
     *
419
     * @param  string  $field  Field array
420
     * @return bool Successful operation true/false.
421
     */
422
    public function addLoadedFieldType($field)
423
    {
424
        $alreadyLoaded = $this->getLoadedFieldTypes();
425
        $type = $this->getFieldTypeWithNamespace($field);
426
427
        if (! in_array($type, $this->getLoadedFieldTypes(), true)) {
428
            $alreadyLoaded[] = $type;
429
            $this->setLoadedFieldTypes($alreadyLoaded);
430
431
            return true;
432
        }
433
434
        return false;
435
    }
436
437
    /**
438
     * Alias of the addLoadedFieldType() method.
439
     * Adds a new field type to the loadedFieldTypes array.
440
     *
441
     * @param  string  $field  Field array
442
     * @return bool Successful operation true/false.
443
     */
444
    public function markFieldTypeAsLoaded($field)
445
    {
446
        return $this->addLoadedFieldType($field);
447
    }
448
449
    /**
450
     * Check if a field type's reasources (CSS and JS) have already been loaded.
451
     *
452
     * @param  string  $field  Field array
453
     * @return bool Whether the field type has been marked as loaded.
454
     */
455
    public function fieldTypeLoaded($field)
456
    {
457
        return in_array($this->getFieldTypeWithNamespace($field), $this->getLoadedFieldTypes());
458
    }
459
460
    /**
461
     * Check if a field type's reasources (CSS and JS) have NOT been loaded.
462
     *
463
     * @param  string  $field  Field array
464
     * @return bool Whether the field type has NOT been marked as loaded.
465
     */
466
    public function fieldTypeNotLoaded($field)
467
    {
468
        return ! in_array($this->getFieldTypeWithNamespace($field), $this->getLoadedFieldTypes());
469
    }
470
471
    /**
472
     * Get a list of all field names for the current operation.
473
     *
474
     * @return array
475
     */
476
    public function getAllFieldNames()
477
    {
478
        return Arr::flatten(Arr::pluck($this->getCleanStateFields(), 'name'));
479
    }
480
481
    /**
482
     * Returns the request without anything that might have been maliciously inserted.
483
     * Only specific field names that have been introduced with addField() are kept in the request.
484
     *
485
     * @param  \Illuminate\Http\Request  $request
486
     * @return array
487
     */
488
    public function getStrippedSaveRequest($request)
489
    {
490
        $setting = $this->getOperationSetting('strippedRequest');
491
492
        // if a closure was passed
493
        if (is_callable($setting)) {
494
            return $setting($request);
495
        }
496
497
        // if an invokable class was passed
498
        // eg. \App\Http\Requests\BackpackStrippedRequest
499
        if (is_string($setting) && class_exists($setting)) {
500
            $setting = new $setting();
501
502
            return is_callable($setting) ? $setting($request) : abort(500, get_class($setting).' is not invokable.');
0 ignored issues
show
Bug introduced by
Are you sure the usage of abort(500, get_class($se.... ' is not invokable.') is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
503
        }
504
505
        return $request->only($this->getAllFieldNames());
506
    }
507
508
    /**
509
     * Check if a field exists, by any given attribute.
510
     *
511
     * @param  string  $attribute  Attribute name on that field definition array.
512
     * @param  string  $value  Value of that attribute on that field definition array.
513
     * @return bool
514
     */
515
    public function hasFieldWhere($attribute, $value)
516
    {
517
        $match = Arr::first($this->getCleanStateFields(), function ($field, $fieldKey) use ($attribute, $value) {
518
            return isset($field[$attribute]) && $field[$attribute] == $value;
519
        });
520
521
        return (bool) $match;
522
    }
523
524
    /**
525
     * Get the first field where a given attribute has the given value.
526
     *
527
     * @param  string  $attribute  Attribute name on that field definition array.
528
     * @param  string  $value  Value of that attribute on that field definition array.
529
     * @return bool
530
     */
531
    public function firstFieldWhere($attribute, $value)
532
    {
533
        return Arr::first($this->getCleanStateFields(), function ($field, $fieldKey) use ($attribute, $value) {
534
            return isset($field[$attribute]) && $field[$attribute] == $value;
535
        });
536
    }
537
538
    /**
539
     * Create and return a CrudField object for that field name.
540
     *
541
     * Enables developers to use a fluent syntax to declare their fields,
542
     * in addition to the existing options:
543
     * - CRUD::addField(['name' => 'price', 'type' => 'number']);
544
     * - CRUD::field('price')->type('number');
545
     *
546
     * And if the developer uses the CrudField object as Field in their CrudController:
547
     * - Field::name('price')->type('number');
548
     *
549
     * @param  string  $name  The name of the column in the db, or model attribute.
550
     * @return CrudField
551
     */
552
    public function field($name)
553
    {
554
        return new CrudField($name);
555
    }
556
}
557