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

222
        $this->/** @scrutinizer ignore-call */ 
223
               setOperationSetting('fields', $fields);
Loading history...
223
    }
224
225
    /**
226
     * Update value of a given key for a current field.
227
     *
228
     * @param  string  $fieldName  The field name
229
     * @param  array  $modifications  An array of changes to be made.
230
     */
231
    public function modifyField($fieldName, $modifications)
232
    {
233
        $fieldsArray = $this->getCleanStateFields();
234
        $field = $this->firstFieldWhere('name', $fieldName);
235
        $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

235
        $fieldKey = $this->getFieldKey(/** @scrutinizer ignore-type */ $field);
Loading history...
236
237
        foreach ($modifications as $attributeName => $attributeValue) {
238
            $fieldsArray[$fieldKey][$attributeName] = $attributeValue;
239
        }
240
241
        $this->enableTabsIfFieldUsesThem($modifications);
242
243
        $this->setOperationSetting('fields', $fieldsArray);
244
    }
245
246
    /**
247
     * Set label for a specific field.
248
     *
249
     * @param  string  $field
250
     * @param  string  $label
251
     */
252
    public function setFieldLabel($field, $label)
253
    {
254
        $this->modifyField($field, ['label' => $label]);
255
    }
256
257
    /**
258
     * Check if field is the first of its type in the given fields array.
259
     * 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).
260
     *
261
     * @param  array  $field  The current field being tested if it's the first of its type.
262
     * @return bool true/false
263
     */
264
    public function checkIfFieldIsFirstOfItsType($field)
265
    {
266
        $fields_array = $this->getCleanStateFields();
267
        $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

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