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

Completed
Pull Request — master (#15)
by
unknown
03:17
created

Crud::addCreateField()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 1
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 5
b 0
f 1
1
<?php
2
3
namespace Backpack\CRUD;
4
5
class Crud
6
{
7
    // --------------
8
    // CRUD variables
9
    // --------------
10
    // These variables are passed to the CRUD views, inside the $crud variable.
11
    // All variables are public, so they can be modified from your EntityCrudController.
12
    // All functions and methods are also public, so they can be used in your EntityCrudController to modify these variables.
13
14
    // TODO: translate $entity_name and $entity_name_plural by default, with english fallback
15
    // TODO: code logic for using either Laravel Authorization or Entrust (whatever one chooses) for access
16
17
    public $model = "\App\Models\Entity"; // what's the namespace for your entity's model
18
    public $route; // what route have you defined for your entity? used for links.
19
    public $entity_name = "entry"; // what name will show up on the buttons, in singural (ex: Add entity)
20
    public $entity_name_plural = "entries"; // what name will show up on the buttons, in plural (ex: Delete 5 entities)
21
22
    public $access = ['list', 'create', 'update', 'delete', /* 'reorder', 'show', 'details_row' */];
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
23
24
    public $reorder = false;
25
    public $reorder_label = false;
26
    public $reorder_max_level = 3;
27
28
    public $details_row = false;
29
30
    public $columns = []; // Define the columns for the table view as an array;
31
    public $create_fields = []; // Define the fields for the "Add new entry" view as an array;
32
    public $update_fields = []; // Define the fields for the "Edit entry" view as an array;
33
    public $fields = []; // Define both create_fields and update_fields in one array; will be overwritten by create_fields and update_fields;
34
35
    public $query;
36
    public $entry;
37
38
    // TONE FIELDS - TODO: find out what he did with them, replicate or delete
39
    public $field_types = [];
40
41
    public $custom_buttons = [];
42
    public $relations = [];
43
    public $sort = [];
44
45
    public $buttons = [''];
46
47
48
49
    // The following methods are used in CrudController or your EntityCrudController to manipulate the variables above.
50
51
52
    /*
53
    |--------------------------------------------------------------------------
54
    |                                   CREATE
55
    |--------------------------------------------------------------------------
56
    */
57
58
    /**
59
     * Insert a row in the database.
60
     *
61
     * @param  [Request] All input values to be inserted.
62
     * @return [Eloquent Collection]
0 ignored issues
show
Documentation introduced by
The doc-type Eloquent">[Eloquent could not be parsed: Unknown type name "[" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
63
     */
64
    public function create($data)
65
    {
66
        $values_to_store = $this->compactFakeFields($data);
67
        $item = $this->model->create($values_to_store);
1 ignored issue
show
Bug introduced by
The method create cannot be called on $this->model (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
68
69
        // if there are any relationships available, also sync those
70
        $this->syncPivot($item, $data);
71
72
        return $item;
73
    }
74
75
76
    /**
77
     * Get all fields needed for the ADD NEW ENTRY form.
78
     *
79
     * @return [array] The fields with attributes and fake attributes.
0 ignored issues
show
Documentation introduced by
The doc-type [array] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
80
     */
81
    public function getCreateFields()
82
    {
83
        return $this->prepareFields(empty($this->create_fields)?$this->fields:$this->create_fields);
0 ignored issues
show
Documentation introduced by
empty($this->create_fiel... : $this->create_fields is of type array, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
84
    }
85
86
    /**
87
     * Get all fields with relation set (model key set on field)
88
     *
89
     * @param [string: create/update]  
90
     * @return [array] The fields with model key set.
0 ignored issues
show
Documentation introduced by
The doc-type [array] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
91
     */
92
    public function getRelationFields($form = 'create')
93
    {
94
        if( $form == 'create' ){
95
            $fields = empty($this->create_fields)?$this->fields:$this->create_fields;
96
        }else{
97
            $fields = empty($this->update_fields)?$this->fields:$this->update_fields;
98
        }
99
100
        $relationFields = [];
101
102
        foreach($fields as $field){
103
            if(isset($field['model']) || isset($field['dependencies'])){
104
                array_push($relationFields, $field);
105
            }
106
        }
107
108
        return $relationFields;
109
    }
110
111
112
    public function syncPivot($model, $data, $form = 'create')
113
    {
114
115
        $relations = $this->getRelationFields($form);
116
        
117
        foreach ($relations as $key => $relation)
118
        {
119
            if ( (isset($relation['pivot']) && $relation['pivot'] ) || isset($relation['dependencies']) ){
120
                if(is_array($relation['name'])){
121
                    foreach($relation['name'] as $relation){
122
                        if(isset($data[$relation])){
123
                            $model->{$relation}()->sync($data[$relation]);
124
                        }else{
125
                             $model->{$relation}()->sync([]);
126
                        }
127
                    }
128
                }else{
129
                    $model->{$relation['name']}()->sync($data[$relation['name']]);
130
                }
131
132
                if( isset($relation['pivotFields']) ){
133
                    foreach($relation['pivotFields'] as $pivotField){
134
                       foreach($data[$pivotField] as $pivot_id =>  $field){
135
                         $model->{$relation['name']}()->updateExistingPivot($pivot_id, [$pivotField => $field]);
136
                       }
137
                    }
138
                }
139
            }
140
        }
141
    }
142
143
144
145
    /**
146
     * Adds a required => true attribute to each field, so that the required asterisc will show up in the create/update forms.
147
     * TODO: make this work, by editing the $this->fields variable.
148
     *
149
     * @param [string or array of strings]
150
     */
151
    public function setRequiredFields($fields, $form = 'both')
0 ignored issues
show
Unused Code introduced by
The parameter $fields is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $form is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
152
    {
153
        // TODO
154
    }
155
156
    /**
157
     * Adds a required => true attribute to this field, so that the required asteris will show up in the create/update forms.
158
     *
159
     * @param [string]
160
     */
161
    public function setRequiredField($field, $form = 'both')
0 ignored issues
show
Unused Code introduced by
The parameter $field is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $form is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
162
    {
163
        // TODO
164
    }
165
166
    /**
167
     * Get all fields that have the required attribute.
168
     * TODO: make this work after making setRequiredFields() work.
169
     *
170
     * @return [array]
0 ignored issues
show
Documentation introduced by
The doc-type [array] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
171
     */
172
    public function getRequiredFields($form = 'both')
0 ignored issues
show
Unused Code introduced by
The parameter $form is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
173
    {
174
        // TODO
175
    }
176
177
178
   /*
179
    |--------------------------------------------------------------------------
180
    |                                   READ
181
    |--------------------------------------------------------------------------
182
    */
183
184
    /**
185
     * Find and retrieve an entry in the database or fail.
186
     *
187
     * @param  [int] The id of the row in the db to fetch.
188
     * @return [Eloquent Collection] The row in the db.
0 ignored issues
show
Documentation introduced by
The doc-type Eloquent">[Eloquent could not be parsed: Unknown type name "[" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
189
     */
190
    public function getEntry($id)
191
    {
192
        $entry = $this->model->findOrFail($id);
1 ignored issue
show
Bug introduced by
The method findOrFail cannot be called on $this->model (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
193
        return $entry->withFakes();
194
    }
195
196
197
    /**
198
     * Get all entries from the database.
199
     *
200
     * @return [Collection of your model]
0 ignored issues
show
Documentation introduced by
The doc-type Collection">[Collection could not be parsed: Unknown type name "[" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
201
     */
202
    public function getEntries()
203
    {
204
        $entries = $this->query->get();
205
206
        // add the fake columns for each entry
207
        foreach ($entries as $key => $entry) {
208
            $entry->addFakes($this->getFakeColumnsAsArray());
209
        }
210
211
        return $entries;
212
    }
213
214
215
    /**
216
     * Get the fields for the create or update forms.
217
     *
218
     * @param  [form] create / update / both - defaults to 'both'
219
     * @param  [integer] the ID of the entity to be edited in the Update form
220
     * @return [array] all the fields that need to be shown and their information
0 ignored issues
show
Documentation introduced by
The doc-type [array] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
221
     */
222
    public function getFields($form, $id = false)
223
    {
224
        switch ($form) {
225
            case 'create':
226
                return $this->getCreateFields();
227
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
228
229
            case 'update':
230
                return $this->getUpdateFields($id);
231
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
232
233
            default:
234
                return $this->getCreateFields();
235
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
236
        }
237
    }
238
239
    /**
240
     * Enable the DETAILS ROW functionality:
241
     *
242
     * In the table view, show a plus sign next to each entry.
243
     * 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.
244
     */
245
    public function enableDetailsRow()
246
    {
247
        $this->details_row = true;
248
    }
249
250
    /**
251
     * Disable the DETAILS ROW functionality:
252
     */
253
    public function disableDetailsRow()
254
    {
255
        $this->details_row = false;
256
    }
257
258
259
260
   /*
261
    |--------------------------------------------------------------------------
262
    |                                   UPDATE
263
    |--------------------------------------------------------------------------
264
    */
265
266
    /**
267
     * Update a row in the database.
268
     *
269
     * @param  [Int] The entity's id
270
     * @param  [Request] All inputs to be updated.
271
     * @return [Eloquent Collection]
0 ignored issues
show
Documentation introduced by
The doc-type Eloquent">[Eloquent could not be parsed: Unknown type name "[" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
272
     */
273 View Code Duplication
    public function update($id, $data)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
274
    {
275
        $item = $this->model->findOrFail($id);
1 ignored issue
show
Bug introduced by
The method findOrFail cannot be called on $this->model (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
276
        $updated = $item->update($this->compactFakeFields($data));
0 ignored issues
show
Unused Code introduced by
$updated is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
277
       
278
        /*if ($updated) */$this->syncPivot($item, $data, 'update');
279
280
        return $item;
281
    }
282
283
284
    /**
285
     * Get all fields needed for the EDIT ENTRY form.
286
     *
287
     * @param  [integer] The id of the entry that is being edited.
288
     * @return [array] The fields with attributes, fake attributes and values.
0 ignored issues
show
Documentation introduced by
The doc-type [array] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
289
     */
290
    public function getUpdateFields($id)
291
    {
292
        $fields = $this->prepareFields(empty($this->update_fields)?$this->fields:$this->update_fields);
0 ignored issues
show
Documentation introduced by
empty($this->update_fiel... : $this->update_fields is of type array, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
293
        $entry = $this->getEntry($id);
294
295
        foreach ($fields as $k => $field) {
0 ignored issues
show
Bug introduced by
The expression $fields of type boolean is not traversable.
Loading history...
296
            // set the value
297
            if (!isset($fields[$k]['value']))
298
            {
299
                if(is_array($field['name'])){
300
                    
301
                    $fields[$k]['value'] = [];
302
                    foreach($field['name'] as  $key => $relation){
303
                        $fields[$k]['value'][] = $entry->{$relation};
304
                    }
305
                
306
                }else{
307
                    $fields[$k]['value'] = $entry->{$field['name']};
308
                }
309
            }
310
        }
311
312
        // always have a hidden input for the entry id
313
        $fields[] = array(
314
                        'name' => 'id',
315
                        'value' => $entry->id,
316
                        'type' => 'hidden'
317
                    );
318
319
        return $fields;
320
    }
321
322
323
324
325
   /*
326
    |--------------------------------------------------------------------------
327
    |                                   DELETE
328
    |--------------------------------------------------------------------------
329
    */
330
331
    /**
332
     * Delete a row from the database.
333
     *
334
     * @param  [int] The id of the item to be deleted.
335
     * @return [bool] Deletion confirmation.
0 ignored issues
show
Documentation introduced by
The doc-type [bool] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
336
     *
337
     * TODO: should this delete items with relations to it too?
338
     */
339
    public function delete($id)
340
    {
341
        return $this->model->destroy($id);
1 ignored issue
show
Bug introduced by
The method destroy cannot be called on $this->model (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
342
    }
343
344
345
346
347
    /*
348
    |--------------------------------------------------------------------------
349
    |                                   REORDER
350
    |--------------------------------------------------------------------------
351
    */
352
353
354
    /**
355
     * Change the order and parents of the given elements, according to the NestedSortable AJAX call.
356
     *
357
     * @param  [Request] The entire request from the NestedSortable AJAX Call.
358
     * @return [integer] The number of items whose position in the tree has been changed.
0 ignored issues
show
Documentation introduced by
The doc-type [integer] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
359
     */
360
    public function updateTreeOrder($request)
361
    {
362
        $count = 0;
363
364
        foreach ($request as $key => $entry) {
365
            if ($entry['item_id'] != "" && $entry['item_id'] != null) {
366
                $item = $this->model->find($entry['item_id']);
1 ignored issue
show
Bug introduced by
The method find cannot be called on $this->model (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
367
                $item->parent_id = $entry['parent_id'];
368
                $item->depth = $entry['depth'];
369
                $item->lft = $entry['left'];
370
                $item->rgt = $entry['right'];
371
                $item->save();
372
373
                $count++;
374
            }
375
        }
376
377
        return $count;
378
    }
379
380
381
    /**
382
     * Enable the Reorder functionality in the CRUD Panel for users that have the been given access to 'reorder' using:
383
     * $this->crud->allowAccess('reorder');
384
     *
385
     * @param  [string] Column name that will be shown on the labels.
386
     * @param  [integer] Maximum hierarchy level to which the elements can be nested (1 = no nesting, just reordering).
387
     */
388
    public function enableReorder($label = 'name', $max_level = 1)
389
    {
390
        $this->reorder = true;
391
        $this->reorder_label = $label;
0 ignored issues
show
Documentation Bug introduced by
The property $reorder_label was declared of type boolean, but $label is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
392
        $this->reorder_max_level = $max_level;
393
    }
394
395
    /**
396
     * Disable the Reorder functionality in the CRUD Panel for all users.
397
     *
398
     */
399
    public function disableReorder()
400
    {
401
        $this->reorder = false;
402
    }
403
404
    /**
405
     * Check if the Reorder functionality is enabled or not.
406
     *
407
     * @return boolean
408
     */
409
    public function isReorderEnabled()
410
    {
411
        return $this->reorder;
412
    }
413
414
415
416
   /*
417
    |--------------------------------------------------------------------------
418
    |                                   CRUD ACCESS
419
    |--------------------------------------------------------------------------
420
    */
421
422
    public function allowAccess($access)
423
    {
424
        // $this->addButtons((array)$access);
0 ignored issues
show
Unused Code Comprehensibility introduced by
78% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
425
        return $this->access = array_merge(array_diff((array)$access, $this->access), $this->access);
426
    }
427
428
    public function denyAccess($access)
429
    {
430
        // $this->removeButtons((array)$access);
0 ignored issues
show
Unused Code Comprehensibility introduced by
78% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
431
        return $this->access = array_diff($this->access, (array)$access);
432
    }
433
434
    /**
435
     * Check if a permission is enabled for a Crud Panel. Return false if not.
436
     *
437
     * @param  [string] Permission.
438
     * @return boolean
439
     */
440
    public function hasAccess($permission)
441
    {
442
        if (!in_array($permission, $this->access))
443
        {
444
            return false;
445
        }
446
        return true;
447
    }
448
449
    /**
450
     * Check if a permission is enabled for a Crud Panel. Fail if not.
451
     *
452
     * @param  [string] Permission.
453
     * @return boolean
454
     */
455
    public function hasAccessOrFail($permission)
456
    {
457
        if (!in_array($permission, $this->access))
458
        {
459
            abort(403, trans('backpack::crud.unauthorized_access'));
460
        }
461
    }
462
463
464
465
    /*
466
    |--------------------------------------------------------------------------
467
    |                               CRUD MANIPULATION
468
    |--------------------------------------------------------------------------
469
    */
470
471
472
473
    // ------------------------------------------------------
474
    // BASICS - model, route, entity_name, entity_name_plural
475
    // ------------------------------------------------------
476
477
    /**
478
     * This function binds the CRUD to its corresponding Model (which extends Eloquent).
479
     * All Create-Read-Update-Delete operations are done using that Eloquent Collection.
480
     *
481
     * @param [string] Full model namespace. Ex: App\Models\Article
482
     */
483 View Code Duplication
    public function setModel($model_namespace)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
484
    {
485
        if (!class_exists($model_namespace)) throw new \Exception('This model does not exist.', 404);
486
487
        $this->model = new $model_namespace();
0 ignored issues
show
Documentation Bug introduced by
It seems like new $model_namespace() of type object is incompatible with the declared type string of property $model.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
488
        $this->query = $this->model->select('*');
489
490
        // $this->setFromDb(); // i think that, by default, the auto-fields functionality should be disabled; otherwise, the workflow changes from "set the fields i need" to "update this crud with whatever i need"; which i personally don't like, because it's more hacky and it assumes you should see what the default offers you, then adapt; I propose we set wether the auto-fields functionality is run for panels with a config variable; the config file should be backpack/crud.php and the variable name should be "autoSetFromDb".
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
491
    }
492
493
    /**
494
     * Get the corresponding Eloquent Model for the CrudController, as defined with the setModel() function;
495
     *
496
     * @return [Eloquent Collection]
0 ignored issues
show
Documentation introduced by
The doc-type Eloquent">[Eloquent could not be parsed: Unknown type name "[" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
497
     */
498
    public function getModel()
499
    {
500
        return $this->model;
501
    }
502
503
    /**
504
     * Set the route for this CRUD.
505
     * Ex: admin/article
506
     *
507
     * @param [string] Route name.
508
     * @param [array] Parameters.
509
     */
510
    public function setRoute($route)
511
    {
512
        $this->route = $route;
513
        $this->initButtons();
514
    }
515
516
    /**
517
     * Set the route for this CRUD using the route name.
518
     * Ex: admin.article
519
     *
520
     * @param [string] Route name.
521
     * @param [array] Parameters.
522
     */
523 View Code Duplication
    public function setRouteName($route, $parameters = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
524
    {
525
        $complete_route = $route.'.index';
526
527
        if (!\Route::has($complete_route)) throw new \Exception('There are no routes for this route name.', 404);
528
529
        $this->route = route($complete_route, $parameters);
530
        $this->initButtons();
531
    }
532
533
    /**
534
     * Get the current CrudController route.
535
     *
536
     * Can be defined in the CrudController with:
537
     * - $this->crud->setRoute('admin/article')
538
     * - $this->crud->setRouteName('admin.article')
539
     * - $this->crud->route = "admin/article"
540
     *
541
     * @return [string]
0 ignored issues
show
Documentation introduced by
The doc-type [string] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
542
     */
543
    public function getRoute()
544
    {
545
        return $this->route;
546
    }
547
548
    /**
549
     * Set the entity name in singular and plural.
550
     * Used all over the CRUD interface (header, add button, reorder button, breadcrumbs).
551
     *
552
     * @param [string] Entity name, in singular. Ex: article
553
     * @param [string] Entity name, in plural. Ex: articles
554
     */
555
    public function setEntityNameStrings($singular, $plural) {
556
        $this->entity_name = $singular;
557
        $this->entity_name_plural = $plural;
558
    }
559
560
561
562
563
    // ------------
564
    // COLUMNS
565
    // ------------
566
567
    /**
568
     * Add a bunch of column names and their details to the CRUD object.
569
     *
570
     * @param [array or multi-dimensional array]
571
     */
572
    public function setColumns($columns)
573
    {
574
        // clear any columns already set
575
        $this->columns = [];
576
577
        // if array, add a column for each of the items
578
        if (is_array($columns) && count($columns)) {
579
            foreach ($columns as $key => $column) {
580
                // if label and other details have been defined in the array
581
                if (is_array($columns[0])) {
582
                    $this->addColumn($column);
583
                }
584
                else
585
                {
586
                    $this->addColumn([
587
                                    'name' => $column,
588
                                    'label' => ucfirst($column),
589
                                    'type' => 'text'
590
                                ]);
591
                }
592
            }
593
        }
594
595
        if (is_string($columns)) {
596
            $this->addColumn([
597
                                'name' => $columns,
598
                                'label' => ucfirst($columns),
599
                                'type' => 'text'
600
                                ]);
601
        }
602
603
        // This was the old setColumns() function, and it did not work:
604
        // $this->columns = array_filter(array_map([$this, 'addDefaultTypeToColumn'], $columns));
0 ignored issues
show
Unused Code Comprehensibility introduced by
61% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
605
    }
606
607
    /**
608
     * Add a column at the end of to the CRUD object's "columns" array.
609
     *
610
     * @param [string or array]
611
     */
612
    public function addColumn($column)
613
    {
614
        // make sure the column has a type
615
        $column_with_details = $this->addDefaultTypeToColumn($column);
0 ignored issues
show
Unused Code introduced by
$column_with_details is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
616
617
        // make sure the column has a label
618
        $column_with_details = $this->addDefaultLabel($column);
619
620
        return array_filter($this->columns[] = $column_with_details);
621
    }
622
623
    /**
624
     * Add multiple columns at the end of the CRUD object's "columns" array.
625
     *
626
     * @param [array of columns]
627
     */
628
    public function addColumns($columns)
629
    {
630
        if (count($columns)) {
631
            foreach ($columns as $key => $column) {
632
                $this->addColumn($column);
633
            }
634
        }
635
    }
636
637
    /**
638
     * Add the default column type to the given Column, inferring the type from the database column type.
639
     *
640
     * @param [column array]
641
     */
642
    public function addDefaultTypeToColumn($column)
643
    {
644
        if (array_key_exists('name', (array)$column))
645
        {
646
            $default_type = $this->getFieldTypeFromDbColumnType($column['name']);
647
            return array_merge(['type' => $default_type], $column);
648
        }
649
650
        return false;
651
    }
652
653
    /**
654
     * If a field or column array is missing the "label" attribute, an ugly error would be show.
655
     * So we add the field Name as a label - it's better than nothing.
656
     *
657
     * @param [field or column]
658
     */
659
    public function addDefaultLabel($array) {
660
        if (!array_key_exists('label', (array)$array) && array_key_exists('name', (array)$array)) {
661
            $array = array_merge(['label' => ucfirst($this->makeLabel($array['name']))], $array);
662
            return $array;
663
        }
664
665
        return $array;
666
    }
667
668
    /**
669
     * Remove multiple columns from the CRUD object using their names.
670
     *
671
     * @param  [column array]
672
     */
673
    public function removeColumns($columns)
674
    {
675
        $this->columns = $this->remove('columns', $columns);
676
    }
677
678
    /**
679
     * Remove a column from the CRUD object using its name.
680
     *
681
     * @param  [column array]
682
     */
683
    public function removeColumn($column)
684
    {
685
        return $this->removeColumns([$column]);
686
    }
687
688
    /**
689
     * Change attributes for multiple columns.
690
     *
691
     * @param [columns arrays]
692
     * @param [attributes and values array]
693
     */
694
    public function setColumnsDetails($columns, $attributes)
695
    {
696
        $this->sync('columns', $columns, $attributes);
697
    }
698
699
    /**
700
     * Change attributes for a certain column.
701
     *
702
     * @param [string] Column name.
703
     * @param [attributes and values array]
704
     */
705
    public function setColumnDetails($column, $attributes)
706
    {
707
        $this->setColumnsDetails([$column], $attributes);
708
    }
709
710
711
    /**
712
     * Order the columns in a certain way.
713
     *
714
     * @param [string] Column name.
715
     * @param [attributes and values array]
716
     */
717
    public function setColumnOrder($columns)
0 ignored issues
show
Unused Code introduced by
The parameter $columns is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
718
    {
719
        // TODO
720
    }
721
722
    // ALIAS of setColumnOrder($columns)
723
    public function setColumnsOrder($columns) { $this->setColumnOrder($columns); }
724
725
726
    // ------------
727
    // FIELDS
728
    // ------------
729
730
731
    /**
732
     * Order the fields in a certain way.
733
     *
734
     * @param [string] Column name.
735
     * @param [attributes and values array]
736
     */
737
    public function setFieldOrder($fields)
0 ignored issues
show
Unused Code introduced by
The parameter $fields is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
738
    {
739
        // TODO
740
    }
741
742
    // ALIAS of setFieldOrder($fields)
743
    public function setFieldsOrder($fields) { $this->setFieldOrder($fields); }
744
745
746
    // ----------------
747
    // ADVANCED QUERIES
748
    // ----------------
749
750
751
    /**
752
     * Add another clause to the query (for ex, a WHERE clause).
753
     *
754
     * Examples:
755
     * // $this->crud->addClause('active');
756
     * $this->crud->addClause('type', 'car');
757
     * $this->crud->addClause('where', 'name', '==', 'car');
758
     * $this->crud->addClause('whereName', 'car');
759
     * $this->crud->addClause('whereHas', 'posts', function($query) {
760
     *     $query->activePosts();
761
     *     });
762
     *
763
     * @param [type]
764
     */
765
    public function addClause($function)
766
    {
767
        return call_user_func_array([$this->query, $function], array_slice(func_get_args(), 1, 3));
768
    }
769
770
    /**
771
     * Order the results of the query in a certain way.
772
     *
773
     * @param  [type]
774
     * @param  string
775
     * @return [type]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
776
     */
777
    public function orderBy($field, $order = 'asc')
778
    {
779
        return $this->query->orderBy($field, $order);
780
    }
781
782
    /**
783
     * Group the results of the query in a certain way.
784
     *
785
     * @param  [type]
786
     * @return [type]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
787
     */
788
    public function groupBy($field)
789
    {
790
        return $this->query->groupBy($field);
791
    }
792
793
    /**
794
     * Limit the number of results in the query.
795
     *
796
     * @param  [number]
797
     * @return [type]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
798
     */
799
    public function limit($number)
800
    {
801
        return $this->query->limit($number);
802
    }
803
804
805
806
    // ------------
807
    // BUTTONS
808
    // ------------
809
810
    // TODO: $this->crud->setButtons(); // default includes edit and delete, with their name, icon, permission, link and class (btn-default)
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
811
    // TODO: $this->crud->addButton();
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
812
    // TODO: $this->crud->removeButton();
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
813
    // TODO: $this->crud->replaceButton();
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
814
815
816
817
    // ------------------------------------------------------
818
    // AUTO-SET-FIELDS-AND-COLUMNS FUNCTIONALITY
819
    // ------------------------------------------------------
820
821
822
    /**
823
     * For a simple CRUD Panel, there should be no need to add/define the fields.
824
     * The public columns in the database will be converted to be fields.
825
     *
826
     */
827
    public function setFromDb()
828
    {
829
        $this->getDbColumnTypes();
830
831
        array_map(function($field) {
832
            // $this->labels[$field] = $this->makeLabel($field);
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
833
834
            $this->fields[] =  [
835
                                'name' => $field,
836
                                'label' => ucfirst($field),
837
                                'value' => '', 'default' => $this->field_types[$field]['default'],
838
                                'type' => $this->getFieldTypeFromDbColumnType($field),
839
                                'values' => [],
840
                                'attributes' => []
841
                                ];
842
843 View Code Duplication
            if (!in_array($field, $this->model->getHidden()))
1 ignored issue
show
Bug introduced by
The method getHidden cannot be called on $this->model (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
844
            {
845
                 $this->columns[] = [
846
                                    'name' => $field,
847
                                    'label' => ucfirst($field),
848
                                    'type' => $this->getFieldTypeFromDbColumnType($field)
849
                                    ];
850
            }
851
852
        }, $this->getDbColumnsNames());
853
    }
854
855
856
    /**
857
     * Get all columns from the database for that table.
858
     *
859
     * @return [array]
0 ignored issues
show
Documentation introduced by
The doc-type [array] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
860
     */
861 View Code Duplication
    public function getDbColumnTypes()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
862
    {
863
        foreach (\DB::select(\DB::raw('SHOW COLUMNS FROM '.$this->model->getTable())) as $column)
1 ignored issue
show
Bug introduced by
The method getTable cannot be called on $this->model (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
864
        {
865
            $this->field_types[$column->Field] = ['type' => trim(preg_replace('/\(\d+\)(.*)/i', '', $column->Type)), 'default' => $column->Default];
866
        }
867
868
        return $this->field_types;
869
    }
870
871
872
    /**
873
     * Intuit a field type, judging from the database column type.
874
     *
875
     * @param  [string] Field name.
876
     * @return [string] Fielt type.
0 ignored issues
show
Documentation introduced by
The doc-type [string] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
877
     */
878 View Code Duplication
    public function getFieldTypeFromDbColumnType($field)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
879
    {
880
        if (!array_key_exists($field, $this->field_types)) return 'text';
881
882
        if ($field == 'password') return 'password';
883
884
        if ($field == 'email') return 'email';
885
886
        switch ($this->field_types[$field]['type'])
887
        {
888
            case 'int':
889
            case 'smallint':
890
            case 'mediumint':
891
            case 'longint':
892
                return 'number';
893
            break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
894
895
            case 'string':
896
            case 'varchar':
897
            case 'set':
898
                return 'text';
899
            break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
900
901
            // case 'enum':
902
            //     return 'enum';
903
            // break;
904
905
            case 'tinyint':
906
                return 'active';
907
            break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
908
909
            case 'text':
910
            case 'mediumtext':
911
            case 'longtext':
912
                return 'textarea';
913
            break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
914
915
            case 'date':
916
                return 'date';
917
            break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
918
919
            case 'datetime':
920
            case 'timestamp':
921
                return 'datetime';
922
            break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
923
            case 'time':
924
                return 'time';
925
            break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
926
927
            default:
928
                return 'text';
929
            break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
930
        }
931
    }
932
933
934
    /**
935
     * Turn a database column name or PHP variable into a pretty label to be shown to the user.
936
     *
937
     * @param  [string]
938
     * @return [string]
0 ignored issues
show
Documentation introduced by
The doc-type [string] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
939
     */
940
    public function makeLabel($value)
941
    {
942
        return trim(preg_replace('/(id|at|\[\])$/i', '', ucfirst(str_replace('_', ' ', $value))));
943
    }
944
945
946
    /**
947
     * Get the database column names, in order to figure out what fields/columns to show in the auto-fields-and-columns functionality.
948
     *
949
     * @return [array] Database column names as an array.
0 ignored issues
show
Documentation introduced by
The doc-type [array] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
950
     */
951 View Code Duplication
    public function getDbColumnsNames()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
952
    {
953
        // Automatically-set columns should be both in the database, and in the $fillable variable on the Eloquent Model
954
        $columns = \Schema::getColumnListing($this->model->getTable());
1 ignored issue
show
Bug introduced by
The method getTable cannot be called on $this->model (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
955
        $fillable = $this->model->getFillable();
1 ignored issue
show
Bug introduced by
The method getFillable cannot be called on $this->model (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
956
957
        if (!empty($fillable)) $columns = array_intersect($columns, $fillable);
958
959
        // but not updated_at, deleted_at
960
        return array_values(array_diff($columns, [$this->model->getKeyName(), 'updated_at', 'deleted_at']));
1 ignored issue
show
Bug introduced by
The method getKeyName cannot be called on $this->model (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
961
    }
962
963
964
965
966
967
968
969
    // -----------------
970
    // Commodity methods
971
    // -----------------
972
973
974
    /**
975
     * Prepare the fields to be shown, stored, updated or created.
976
     *
977
     * Makes sure $this->crud->fields is in the proper format (array of arrays);
978
     * Makes sure $this->crud->fields also contains the id of the current item;
979
     * Makes sure $this->crud->fields also contains the values for each field;
980
     *
981
     */
982
    public function prepareFields($fields = false)
983
    {
984
        // if no field type is defined, assume the "text" field type
985
        foreach ($fields as $k => $field) {
0 ignored issues
show
Bug introduced by
The expression $fields of type boolean is not traversable.
Loading history...
986
                if (!isset($fields[$k]['type'])) {
987
                    $fields[$k]['type'] = 'text';
988
                }
989
            }
990
991
        return $fields;
992
    }
993
994
995
996
    /**
997
     * Refactor the request array to something that can be passed to the model's create or update function.
998
     * The resulting array will only include the fields that are stored in the database and their values,
999
     * plus the '_token' and 'redirect_after_save' variables.
1000
     *
1001
     * @param   Request     $request - everything that was sent from the form, usually \Request::all()
1002
     * @return  array
1003
     */
1004
    public function compactFakeFields($request) {
1005
1006
        // $this->prepareFields();
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1007
1008
        $fake_field_columns_to_encode = [];
1009
1010
        // go through each defined field
1011
        foreach ($this->fields as $k => $field) {
1012
            // if it's a fake field
1013
            if (isset($this->fields[$k]['fake']) && $this->fields[$k]['fake'] == true) {
1014
                // add it to the request in its appropriate variable - the one defined, if defined
1015
                if (isset($this->fields[$k]['store_in'])) {
1016
                    $request[$this->fields[$k]['store_in']][$this->fields[$k]['name']] = $request[$this->fields[$k]['name']];
1017
1018
                    $remove_fake_field = array_pull($request, $this->fields[$k]['name']);
0 ignored issues
show
Unused Code introduced by
$remove_fake_field is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1019 View Code Duplication
                    if (!in_array($this->fields[$k]['store_in'], $fake_field_columns_to_encode, true)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1020
                        array_push($fake_field_columns_to_encode, $this->fields[$k]['store_in']);
1021
                    }
1022
                } else //otherwise in the one defined in the $crud variable
1023
                {
1024
                    $request['extras'][$this->fields[$k]['name']] = $request[$this->fields[$k]['name']];
1025
1026
                    $remove_fake_field = array_pull($request, $this->fields[$k]['name']);
0 ignored issues
show
Unused Code introduced by
$remove_fake_field is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1027
                    if (!in_array('extras', $fake_field_columns_to_encode, true)) {
1028
                        array_push($fake_field_columns_to_encode, 'extras');
1029
                    }
1030
                }
1031
            }
1032
        }
1033
1034
        // json_encode all fake_value columns in the database, so they can be properly stored and interpreted
1035
        if (count($fake_field_columns_to_encode)) {
1036
            foreach ($fake_field_columns_to_encode as $key => $value) {
1037
                $request[$value] = json_encode($request[$value]);
1038
            }
1039
        }
1040
1041
        // if there are no fake fields defined, this will just return the original Request in full
1042
        // since no modifications or additions have been made to $request
1043
        return $request;
1044
    }
1045
1046
1047
    /**
1048
     * Returns an array of database columns names, that are used to store fake values.
1049
     * Returns ['extras'] if no columns have been found.
1050
     *
1051
     */
1052
    public function getFakeColumnsAsArray() {
1053
1054
        // $this->prepareFields();
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1055
1056
        $fake_field_columns_to_encode = [];
1057
1058
        foreach ($this->fields as $k => $field) {
1059
            // if it's a fake field
1060
            if (isset($this->fields[$k]['fake']) && $this->fields[$k]['fake'] == true) {
1061
                // add it to the request in its appropriate variable - the one defined, if defined
1062
                if (isset($this->fields[$k]['store_in'])) {
1063 View Code Duplication
                    if (!in_array($this->fields[$k]['store_in'], $fake_field_columns_to_encode, true)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1064
                        array_push($fake_field_columns_to_encode, $this->fields[$k]['store_in']);
1065
                    }
1066
                } else //otherwise in the one defined in the $crud variable
1067
                {
1068
                    if (!in_array('extras', $fake_field_columns_to_encode, true)) {
1069
                        array_push($fake_field_columns_to_encode, 'extras');
1070
                    }
1071
                }
1072
            }
1073
        }
1074
1075
        if (!count($fake_field_columns_to_encode)) {
1076
            return ['extras'];
1077
        }
1078
1079
        return $fake_field_columns_to_encode;
1080
    }
1081
1082
1083
1084
1085
1086
1087
1088
1089
    // ----------------------------------
1090
    // Miscellaneous functions or methods
1091
    // ----------------------------------
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
    // ------------
1106
    // TONE FUNCTIONS - UNDOCUMENTED, UNTESTED, SOME MAY BE USED IN THIS FILE
1107
    // ------------
1108
    //
1109
    // TODO:
1110
    // - figure out if they are really needed
1111
    // - comments inside the function to explain how they work
1112
    // - write docblock for them
1113
    // - place in the correct section above (CREATE, READ, UPDATE, DELETE, ACCESS, MANIPULATION)
1114
1115
1116
1117
    public function addButton($button)
1118
    {
1119
        array_unshift($this->buttons, $button);
1120
    }
1121
1122
    public function buttons()
1123
    {
1124
        return $this->buttons;
1125
    }
1126
1127
    public function addCustomButton($button)
1128
    {
1129
        array_unshift($this->custom_buttons, $button);
1130
    }
1131
1132
    public function customButtons()
1133
    {
1134
        return $this->custom_buttons;
1135
    }
1136
1137
    public function showButtons()
1138
    {
1139
        return !empty($this->buttons) && !(count($this->buttons) == 1 && array_key_exists('add', $this->buttons));
1140
    }
1141
1142 View Code Duplication
    public function initButtons()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1143
    {
1144
        $this->buttons = [
1145
            'add' => ['route' => "{$this->route}/create", 'label' => trans('crud::crud.buttons.add'), 'class' => '', 'hide' => [], 'icon' => 'fa-plus-circle', 'extra' => []],
1146
            'view' => ['route' => "{$this->route}/%d", 'label' => trans('crud::crud.buttons.view'), 'class' => '', 'hide' => [], 'icon' => 'fa-eye', 'extra' => []],
1147
            'edit' => ['route' => "{$this->route}/%d/edit", 'label' => trans('crud::crud.buttons.edit'), 'class' => '', 'hide' => [], 'icon' => 'fa-edit', 'extra' => []],
1148
            'delete' => ['route' => "{$this->route}/%d", 'label' => trans('crud::crud.buttons.delete'), 'class' => '', 'hide' => [], 'icon' => 'fa-trash', 'extra' => ['data-confirm' => trans('crud::crud.confirm.delete'), 'data-type' => 'delete']],
1149
        ];
1150
    }
1151
1152
    public function removeButtons($buttons)
1153
    {
1154
        foreach ($buttons as $button)
1155
        {
1156
            unset($this->buttons[$button]);
1157
        }
1158
1159
        return $this->buttons;
1160
    }
1161
1162
1163
1164
1165
1166
1167
1168
1169
    public function getColumns()
1170
    {
1171
        return $this->sort('columns');
1172
    }
1173
1174
    public function orderColumns($order)
1175
    {
1176
        $this->setSort('columns', (array)$order);
1177
    }
1178
1179
1180
1181
1182
1183
1184
    public function setFields($fields)
1185
    {
1186
        $this->addMultiple('fields', $fields);
1187
    }
1188
1189
    // [name, label, value, default, type, required, hint, values[id => value], attributes[class, id, data-, for editor: data-config="basic|medium|full"], callback => [$this, 'methodName'], callback_create => [$this, 'methodName'], callback_edit => [$this, 'methodName'], callback_view => [$this, 'methodName']]
0 ignored issues
show
Unused Code Comprehensibility introduced by
49% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1190
    public function addField($field)
1191
    {
1192
        return $this->add('fields', $field);
1193
    }
1194
1195
    public function updateFields($fields, $attributes)
1196
    {
1197
        $this->sync('fields', $fields, $attributes);
1198
    }
1199
1200
    public function removeFields($fields)
1201
    {
1202
        $this->fields = $this->remove('fields', $fields);
1203
        $this->removeColumns($fields);
1204
    }
1205
1206
    public function setCreateFields($fields)
1207
    {
1208
        $this->addMultiple('create_fields', $fields);
1209
    }
1210
1211
    public function addCreateField($field)
1212
    {
1213
       return $this->add('create_fields', $field);
1214
    }
1215
1216
     public function setUpdateFields($fields)
1217
    {
1218
        $this->addMultiple('update_fields', $fields);
1219
    }
1220
1221
    public function addUpdateField($field)
1222
    {
1223
        return $this->add('update_fields', $field);
1224
    }
1225
1226 View Code Duplication
    public function fields()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1227
    {
1228
        if (!$this->entry && !empty($this->create_fields))
1229
        {
1230
            $this->syncRelations('create_fields');
1231
1232
            return $this->create_fields;
1233
        }
1234
1235
        if ($this->entry && !empty($this->update_fields))
1236
        {
1237
            $this->syncRelations('update_fields');
1238
            $this->addFieldsValue();
1239
1240
            return $this->update_fields;
1241
        }
1242
1243
        $this->syncRelations('fields');
1244
        $this->addFieldsValue();
1245
1246
        return $this->sort('fields');
1247
    }
1248
1249
    public function orderFields($order)
1250
    {
1251
        $this->setSort('fields', (array)$order);
1252
    }
1253
1254
1255
    public function syncField($field)
1256
    {
1257 View Code Duplication
        if (array_key_exists('name', (array)$field)) return array_merge(['type' => $this->getFieldTypeFromDbColumnType($field['name']), 'value' => '', 'default' => null, 'values' => [], 'attributes' => []], $field);
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1258
1259
        return false;
1260
    }
1261
1262
1263
1264
1265
1266
    // iti pune valorile pe field-uri la EDIT
1267 View Code Duplication
    public function addFieldsValue()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1268
    {
1269
        if ($this->entry)
1270
        {
1271
            $fields = !empty($this->update_fields) ? 'update_fields' : 'fields';
1272
1273
            foreach ($this->{$fields} as $key => $field)
1274
            {
1275
                if (array_key_exists($field['name'], $this->relations) && $this->relations[$field['name']]['pivot']) $this->{$fields}[$key]['value'] = $this->entry->{$this->relations[$field['name']]['name']}()->lists($this->relations[$field['name']]['model']->getKeyName())->toArray();
1276
                    else $this->{$fields}[$key]['value'] = $this->entry->{$field['name']};
1277
            }
1278
        }
1279
    }
1280
1281
    public function add($entity, $field)
1282
    {
1283
        return array_filter($this->{$entity}[] = $this->syncField($field));
1284
    }
1285
1286
    public function addMultiple($entity, $field)
0 ignored issues
show
Unused Code introduced by
The parameter $field is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1287
    {
1288
        $this->{$entity} = array_filter(array_map([$this, 'syncField'], $fields));
0 ignored issues
show
Bug introduced by
The variable $fields does not exist. Did you mean $field?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
1289
    }
1290
1291 View Code Duplication
    public function sync($type, $fields, $attributes)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1292
    {
1293
        if (!empty($this->{$type}))
1294
        {
1295
            $this->{$type} = array_map(function($field) use ($fields, $attributes) {
1296
                if (in_array($field['name'], (array)$fields)) $field = array_merge($field, $attributes);
1297
1298
                return $field;
1299
            }, $this->{$type});
1300
        }
1301
    }
1302
1303
1304
1305
    public function remove($entity, $fields)
1306
    {
1307
        return array_values(array_filter($this->{$entity}, function($field) use ($fields) { return !in_array($field['name'], (array)$fields);}));
1308
    }
1309
1310
    public function setSort($items, $order)
1311
    {
1312
        $this->sort[$items] = $order;
1313
    }
1314
1315 View Code Duplication
    public function sort($items)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1316
    {
1317
        if (array_key_exists($items, $this->sort))
1318
        {
1319
            $elements = [];
1320
1321
            foreach ($this->sort[$items] as $item)
1322
            {
1323
                if (is_numeric($key = array_search($item, array_column($this->{$items}, 'name')))) $elements[] = $this->{$items}[$key];
1324
            }
1325
1326
            return $this->{$items} = array_merge($elements, array_filter($this->{$items}, function($item) use($items) {return !in_array($item['name'], $this->sort[$items]);}));
1327
        }
1328
1329
        return $this->{$items};
1330
    }
1331
1332
1333
1334
1335
1336
    // cred ca ia valorile din tabela de legatura ca sa ti le afiseze in select
1337 View Code Duplication
    public function getRelationValues($model, $field, $where = [], $order = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1338
    {
1339
        $order = (array)$order;
1340
        $values = $model->select('*');
1341
1342
        if (!empty($where)) call_user_func_array([$values, $where[0]], array_slice($where, 1));
1343
1344
        if (!empty($order)) call_user_func_array([$values, 'orderBy'], $order);
1345
1346
        return $values->get()->lists($field, $model->getKeyName())->toArray();
1347
    }
1348
1349
    // face un fel de merge intre ce ii dai si ce e in CRUD
1350 View Code Duplication
    public function syncRelations($entity)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1351
    {
1352
        foreach ($this->relations as $field => $relation) {
1353
            if ($relation['pivot']) $this->add($entity, ['name' => $field, 'type' => 'multiselect', 'value' => [], 'values' => $this->relations[$field]['values']]);
1354
                else $this->sync($entity, $field, ['type' => 'select', 'values' => $this->relations[$field]['values']]);
1355
        }
1356
    }
1357
1358
1359
1360
}