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
Push — master ( 759348...75fc1b )
by Cristian
03:32
created

Crud::setRequiredFields()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 4
rs 10
c 2
b 0
f 0
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
34
    public $query;
35
    public $entry;
36
37
    // TONE FIELDS - TODO: find out what he did with them, replicate or delete
38
    public $field_types = [];
39
40
    public $custom_buttons = [];
41
    public $relations = [];
42
    public $sort = [];
43
44
    public $buttons = [''];
45
46
47
48
    // The following methods are used in CrudController or your EntityCrudController to manipulate the variables above.
49
50
51
    /*
52
    |--------------------------------------------------------------------------
53
    |                                   CREATE
54
    |--------------------------------------------------------------------------
55
    */
56
57
    /**
58
     * Insert a row in the database.
59
     *
60
     * @param  [Request] All input values to be inserted.
61
     * @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...
62
     */
63
    public function create($data)
64
    {
65
        $values_to_store = $this->compactFakeFields($data, 'create');
66
        $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...
67
68
        // if there are any relationships available, also sync those
69
        $this->syncPivot($item, $data);
70
71
        return $item;
72
    }
73
74
75
    /**
76
     * Get all fields needed for the ADD NEW ENTRY form.
77
     *
78
     * @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...
79
     */
80
    public function getCreateFields()
81
    {
82
        return $this->create_fields;
83
    }
84
85
    /**
86
     * Get all fields with relation set (model key set on field)
87
     *
88
     * @param [string: create/update/both]
89
     * @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...
90
     */
91
    public function getRelationFields($form = 'create')
92
    {
93
        if ($form == 'create')
94
        {
95
            $fields = $this->create_fields;
96
        }
97
        else
98
        {
99
            $fields = $this->update_fields;
100
        }
101
102
        $relationFields = [];
103
104
        foreach($fields as $field){
105
            if (isset($field['model']))
106
            {
107
                array_push($relationFields, $field);
108
            }
109
110
            if (isset($field['subfields']) &&
111
                is_array($field['subfields']) &&
112
                count($field['subfields']))
113
            {
114
                foreach ($field['subfields'] as $subfield)
115
                {
116
                    array_push($relationFields, $subfield);
117
                }
118
            }
119
        }
120
121
        return $relationFields;
122
    }
123
124
125
    public function syncPivot($model, $data, $form = 'create')
126
    {
127
128
        $fields_with_relationships = $this->getRelationFields($form);
129
130
        foreach ($fields_with_relationships as $key => $field)
131
        {
132
            if (isset($field['pivot']) && $field['pivot'] )
133
            {
134
                $values = isset($data[$field['name']])?$data[$field['name']]:[];
135
                $model->{$field['name']}()->sync($values);
136
137
                if( isset($field['pivotFields']) ){
138
                    foreach($field['pivotFields'] as $pivotField){
139
                       foreach($data[$pivotField] as $pivot_id =>  $field){
140
                         $model->{$field['name']}()->updateExistingPivot($pivot_id, [$pivotField => $field]);
141
                       }
142
                    }
143
                }
144
            }
145
        }
146
    }
147
148
149
150
    /**
151
     * Adds a required => true attribute to each field, so that the required asterisc will show up in the create/update forms.
152
     * TODO: make this work, by editing the $this->fields variable and all fields.
153
     *
154
     * @param [string or array of strings]
155
     */
156
    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...
157
    {
158
        // TODO
159
    }
160
161
    /**
162
     * Adds a required => true attribute to this field, so that the required asteris will show up in the create/update forms.
163
     *
164
     * @param [string]
165
     */
166
    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...
167
    {
168
        // TODO
169
    }
170
171
    /**
172
     * Get all fields that have the required attribute.
173
     * TODO: make this work after making setRequiredFields() work.
174
     *
175
     * @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...
176
     */
177
    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...
178
    {
179
        // TODO
180
    }
181
182
183
   /*
184
    |--------------------------------------------------------------------------
185
    |                                   READ
186
    |--------------------------------------------------------------------------
187
    */
188
189
    /**
190
     * Find and retrieve an entry in the database or fail.
191
     *
192
     * @param  [int] The id of the row in the db to fetch.
193
     * @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...
194
     */
195
    public function getEntry($id)
196
    {
197
        $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...
198
        return $entry->withFakes();
199
    }
200
201
202
    /**
203
     * Get all entries from the database.
204
     *
205
     * @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...
206
     */
207
    public function getEntries()
208
    {
209
        $entries = $this->query->get();
210
211
        // add the fake columns for each entry
212
        foreach ($entries as $key => $entry) {
213
            $entry->addFakes($this->getFakeColumnsAsArray());
214
        }
215
216
        return $entries;
217
    }
218
219
220
    /**
221
     * Get the fields for the create or update forms.
222
     *
223
     * @param  [form] create / update / both - defaults to 'both'
224
     * @param  [integer] the ID of the entity to be edited in the Update form
225
     * @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...
226
     */
227
    public function getFields($form, $id = false)
228
    {
229
        switch (strtolower($form)) {
230
            case 'create':
231
                return $this->getCreateFields();
232
                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...
233
234
            case 'update':
235
                return $this->getUpdateFields($id);
236
                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...
237
238
            default:
239
                return $this->getCreateFields();
240
                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...
241
        }
242
    }
243
244
    /**
245
     * Enable the DETAILS ROW functionality:
246
     *
247
     * In the table view, show a plus sign next to each entry.
248
     * 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.
249
     */
250
    public function enableDetailsRow()
251
    {
252
        $this->details_row = true;
253
    }
254
255
    /**
256
     * Disable the DETAILS ROW functionality:
257
     */
258
    public function disableDetailsRow()
259
    {
260
        $this->details_row = false;
261
    }
262
263
264
265
   /*
266
    |--------------------------------------------------------------------------
267
    |                                   UPDATE
268
    |--------------------------------------------------------------------------
269
    */
270
271
    /**
272
     * Update a row in the database.
273
     *
274
     * @param  [Int] The entity's id
275
     * @param  [Request] All inputs to be updated.
276
     * @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...
277
     */
278
    public function update($id, $data)
279
    {
280
        $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...
281
        $updated = $item->update($this->compactFakeFields($data, 'update'));
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...
282
283
        /*if ($updated) */$this->syncPivot($item, $data, 'update');
284
285
        return $item;
286
    }
287
288
289
    /**
290
     * Get all fields needed for the EDIT ENTRY form.
291
     *
292
     * @param  [integer] The id of the entry that is being edited.
293
     * @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...
294
     */
295
    public function getUpdateFields($id)
296
    {
297
        $fields = $this->update_fields;
298
        $entry = $this->getEntry($id);
299
300
        foreach ($fields as $k => $field) {
301
            // set the value
302
            if (!isset($fields[$k]['value']))
303
            {
304
                if (isset($field['subfields']))
305
                    {
306
                    $fields[$k]['value'] = [];
307
                    foreach($field['subfields'] as $key => $subfield){
308
                        $fields[$k]['value'][] = $entry->{$subfield['name']};
309
                    }
310
311
                }else{
312
                    $fields[$k]['value'] = $entry->{$field['name']};
313
                }
314
            }
315
        }
316
317
        // always have a hidden input for the entry id
318
        $fields['id'] = array(
319
                        'name' => 'id',
320
                        'value' => $entry->id,
321
                        'type' => 'hidden'
322
                    );
323
324
        return $fields;
325
    }
326
327
328
329
330
   /*
331
    |--------------------------------------------------------------------------
332
    |                                   DELETE
333
    |--------------------------------------------------------------------------
334
    */
335
336
    /**
337
     * Delete a row from the database.
338
     *
339
     * @param  [int] The id of the item to be deleted.
340
     * @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...
341
     *
342
     * TODO: should this delete items with relations to it too?
343
     */
344
    public function delete($id)
345
    {
346
        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...
347
    }
348
349
350
351
352
    /*
353
    |--------------------------------------------------------------------------
354
    |                                   REORDER
355
    |--------------------------------------------------------------------------
356
    */
357
358
359
    /**
360
     * Change the order and parents of the given elements, according to the NestedSortable AJAX call.
361
     *
362
     * @param  [Request] The entire request from the NestedSortable AJAX Call.
363
     * @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...
364
     */
365
    public function updateTreeOrder($request)
366
    {
367
        $count = 0;
368
369
        foreach ($request as $key => $entry) {
370
            if ($entry['item_id'] != "" && $entry['item_id'] != null) {
371
                $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...
372
                $item->parent_id = $entry['parent_id'];
373
                $item->depth = $entry['depth'];
374
                $item->lft = $entry['left'];
375
                $item->rgt = $entry['right'];
376
                $item->save();
377
378
                $count++;
379
            }
380
        }
381
382
        return $count;
383
    }
384
385
386
    /**
387
     * Enable the Reorder functionality in the CRUD Panel for users that have the been given access to 'reorder' using:
388
     * $this->crud->allowAccess('reorder');
389
     *
390
     * @param  [string] Column name that will be shown on the labels.
391
     * @param  [integer] Maximum hierarchy level to which the elements can be nested (1 = no nesting, just reordering).
392
     */
393
    public function enableReorder($label = 'name', $max_level = 1)
394
    {
395
        $this->reorder = true;
396
        $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...
397
        $this->reorder_max_level = $max_level;
398
    }
399
400
    /**
401
     * Disable the Reorder functionality in the CRUD Panel for all users.
402
     *
403
     */
404
    public function disableReorder()
405
    {
406
        $this->reorder = false;
407
    }
408
409
    /**
410
     * Check if the Reorder functionality is enabled or not.
411
     *
412
     * @return boolean
413
     */
414
    public function isReorderEnabled()
415
    {
416
        return $this->reorder;
417
    }
418
419
420
421
   /*
422
    |--------------------------------------------------------------------------
423
    |                                   CRUD ACCESS
424
    |--------------------------------------------------------------------------
425
    */
426
427
    public function allowAccess($access)
428
    {
429
        // $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...
430
        return $this->access = array_merge(array_diff((array)$access, $this->access), $this->access);
431
    }
432
433
    public function denyAccess($access)
434
    {
435
        // $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...
436
        return $this->access = array_diff($this->access, (array)$access);
437
    }
438
439
    /**
440
     * Check if a permission is enabled for a Crud Panel. Return false if not.
441
     *
442
     * @param  [string] Permission.
443
     * @return boolean
444
     */
445
    public function hasAccess($permission)
446
    {
447
        if (!in_array($permission, $this->access))
448
        {
449
            return false;
450
        }
451
        return true;
452
    }
453
454
    /**
455
     * Check if a permission is enabled for a Crud Panel. Fail if not.
456
     *
457
     * @param  [string] Permission.
458
     * @return boolean
459
     */
460
    public function hasAccessOrFail($permission)
461
    {
462
        if (!in_array($permission, $this->access))
463
        {
464
            abort(403, trans('backpack::crud.unauthorized_access'));
465
        }
466
    }
467
468
469
470
    /*
471
    |--------------------------------------------------------------------------
472
    |                               CRUD MANIPULATION
473
    |--------------------------------------------------------------------------
474
    */
475
476
477
478
    // ------------------------------------------------------
479
    // BASICS - model, route, entity_name, entity_name_plural
480
    // ------------------------------------------------------
481
482
    /**
483
     * This function binds the CRUD to its corresponding Model (which extends Eloquent).
484
     * All Create-Read-Update-Delete operations are done using that Eloquent Collection.
485
     *
486
     * @param [string] Full model namespace. Ex: App\Models\Article
487
     */
488
    public function setModel($model_namespace)
489
    {
490
        if (!class_exists($model_namespace)) throw new \Exception('This model does not exist.', 404);
491
492
        $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...
493
        $this->query = $this->model->select('*');
494
495
        // $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...
496
    }
497
498
    /**
499
     * Get the corresponding Eloquent Model for the CrudController, as defined with the setModel() function;
500
     *
501
     * @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...
502
     */
503
    public function getModel()
504
    {
505
        return $this->model;
506
    }
507
508
    /**
509
     * Set the route for this CRUD.
510
     * Ex: admin/article
511
     *
512
     * @param [string] Route name.
513
     * @param [array] Parameters.
514
     */
515
    public function setRoute($route)
516
    {
517
        $this->route = $route;
518
        $this->initButtons();
519
    }
520
521
    /**
522
     * Set the route for this CRUD using the route name.
523
     * Ex: admin.article
524
     *
525
     * @param [string] Route name.
526
     * @param [array] Parameters.
527
     */
528
    public function setRouteName($route, $parameters = [])
529
    {
530
        $complete_route = $route.'.index';
531
532
        if (!\Route::has($complete_route)) throw new \Exception('There are no routes for this route name.', 404);
533
534
        $this->route = route($complete_route, $parameters);
535
        $this->initButtons();
536
    }
537
538
    /**
539
     * Get the current CrudController route.
540
     *
541
     * Can be defined in the CrudController with:
542
     * - $this->crud->setRoute('admin/article')
543
     * - $this->crud->setRouteName('admin.article')
544
     * - $this->crud->route = "admin/article"
545
     *
546
     * @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...
547
     */
548
    public function getRoute()
549
    {
550
        return $this->route;
551
    }
552
553
    /**
554
     * Set the entity name in singular and plural.
555
     * Used all over the CRUD interface (header, add button, reorder button, breadcrumbs).
556
     *
557
     * @param [string] Entity name, in singular. Ex: article
558
     * @param [string] Entity name, in plural. Ex: articles
559
     */
560
    public function setEntityNameStrings($singular, $plural) {
561
        $this->entity_name = $singular;
562
        $this->entity_name_plural = $plural;
563
    }
564
565
566
567
568
    // ------------
569
    // COLUMNS
570
    // ------------
571
572
    /**
573
     * Add a bunch of column names and their details to the CRUD object.
574
     *
575
     * @param [array or multi-dimensional array]
576
     */
577
    public function setColumns($columns)
578
    {
579
        // clear any columns already set
580
        $this->columns = [];
581
582
        // if array, add a column for each of the items
583
        if (is_array($columns) && count($columns)) {
584
            foreach ($columns as $key => $column) {
585
                // if label and other details have been defined in the array
586
                if (is_array($columns[0])) {
587
                    $this->addColumn($column);
588
                }
589
                else
590
                {
591
                    $this->addColumn([
592
                                    'name' => $column,
593
                                    'label' => ucfirst($column),
594
                                    'type' => 'text'
595
                                ]);
596
                }
597
            }
598
        }
599
600
        if (is_string($columns)) {
601
            $this->addColumn([
602
                                'name' => $columns,
603
                                'label' => ucfirst($columns),
604
                                'type' => 'text'
605
                                ]);
606
        }
607
608
        // This was the old setColumns() function, and it did not work:
609
        // $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...
610
    }
611
612
    /**
613
     * Add a column at the end of to the CRUD object's "columns" array.
614
     *
615
     * @param [string or array]
616
     */
617
    public function addColumn($column)
618
    {
619
        // make sure the column has a type
620
        $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...
621
622
        // make sure the column has a label
623
        $column_with_details = $this->addDefaultLabel($column);
624
625
        return array_filter($this->columns[] = $column_with_details);
626
    }
627
628
    /**
629
     * Add multiple columns at the end of the CRUD object's "columns" array.
630
     *
631
     * @param [array of columns]
632
     */
633
    public function addColumns($columns)
634
    {
635
        if (count($columns)) {
636
            foreach ($columns as $key => $column) {
637
                $this->addColumn($column);
638
            }
639
        }
640
    }
641
642
    /**
643
     * Add the default column type to the given Column, inferring the type from the database column type.
644
     *
645
     * @param [column array]
646
     */
647
    public function addDefaultTypeToColumn($column)
648
    {
649
        if (array_key_exists('name', (array)$column))
650
        {
651
            $default_type = $this->getFieldTypeFromDbColumnType($column['name']);
652
            return array_merge(['type' => $default_type], $column);
653
        }
654
655
        return false;
656
    }
657
658
    /**
659
     * If a field or column array is missing the "label" attribute, an ugly error would be show.
660
     * So we add the field Name as a label - it's better than nothing.
661
     *
662
     * @param [field or column]
663
     */
664
    public function addDefaultLabel($array) {
665
        if (!array_key_exists('label', (array)$array) && array_key_exists('name', (array)$array)) {
666
            $array = array_merge(['label' => ucfirst($this->makeLabel($array['name']))], $array);
667
            return $array;
668
        }
669
670
        return $array;
671
    }
672
673
    /**
674
     * Remove multiple columns from the CRUD object using their names.
675
     *
676
     * @param  [column array]
677
     */
678
    public function removeColumns($columns)
679
    {
680
        $this->columns = $this->remove('columns', $columns);
0 ignored issues
show
Bug introduced by
The method remove() does not exist on Backpack\CRUD\Crud. Did you maybe mean removeColumns()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
681
    }
682
683
    /**
684
     * Remove a column from the CRUD object using its name.
685
     *
686
     * @param  [column array]
687
     */
688
    public function removeColumn($column)
689
    {
690
        return $this->removeColumns([$column]);
691
    }
692
693
    /**
694
     * Change attributes for multiple columns.
695
     *
696
     * @param [columns arrays]
697
     * @param [attributes and values array]
698
     */
699
    public function setColumnsDetails($columns, $attributes)
700
    {
701
        $this->sync('columns', $columns, $attributes);
702
    }
703
704
    /**
705
     * Change attributes for a certain column.
706
     *
707
     * @param [string] Column name.
708
     * @param [attributes and values array]
709
     */
710
    public function setColumnDetails($column, $attributes)
711
    {
712
        $this->setColumnsDetails([$column], $attributes);
713
    }
714
715
716
    /**
717
     * Order the columns in a certain way.
718
     *
719
     * @param [string] Column name.
720
     * @param [attributes and values array]
721
     */
722
    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...
723
    {
724
        // TODO
725
    }
726
727
    // ALIAS of setColumnOrder($columns)
728
    public function setColumnsOrder($columns) { $this->setColumnOrder($columns); }
729
730
731
    // ------------
732
    // FIELDS
733
    // ------------
734
735
    /**
736
     * Add a field to the create/update form or both.
737
     * @param [string] $name    Field name (the column name in the db in most cases)
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...
Bug introduced by
There is no parameter named $name. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
738
     * @param [array] $options Field-type-specific 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...
Bug introduced by
There is no parameter named $options. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
739
     * @param string $form    The form to add the field to (create/update/both)
740
     */
741
    public function addField($field, $form='both')
742
    {
743
        // if the field_defition_array array is a string, it means the programmer was lazy and has only passed the name
744
        // set some default values, so the field will still work
745
        if (is_string($field))
746
        {
747
            $complete_field_array['name'] = $field;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$complete_field_array was never initialized. Although not strictly required by PHP, it is generally a good practice to add $complete_field_array = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
748
        }
749
        else
750
        {
751
            $complete_field_array = $field;
752
        }
753
754
        // if the label is missing, we should set it
755
        if (!isset($complete_field_array['label']))
756
            $complete_field_array['label'] = ucfirst($complete_field_array['name']);
757
758
        // if the field type is missing, we should set it
759
        if (!isset($complete_field_array['type']))
760
            $complete_field_array['type'] = $this->getFieldTypeFromDbColumnType($complete_field_array['name']);
761
762
        // store the field information into the correct variable on the CRUD object
763
        switch (strtolower($form)) {
764
            case 'create':
765
                $this->create_fields[$complete_field_array['name']] = $complete_field_array;
766
                break;
767
768
            case 'update':
769
                $this->update_fields[$complete_field_array['name']] = $complete_field_array;
770
                break;
771
772
            default:
773
                $this->create_fields[$complete_field_array['name']] = $complete_field_array;
774
                $this->update_fields[$complete_field_array['name']] = $complete_field_array;
775
                break;
776
        }
777
    }
778
779
    public function addFields($fields, $form='both')
780
    {
781
        if (count($fields)) {
782
            foreach ($fields as $field) {
783
                $this->addField($field, $form);
784
            }
785
        }
786
    }
787
788
    /**
789
     * Remove a certain field from the create/update/both forms by its name.
790
     * @param  string $name Field name (as defined with the addField() procedure)
791
     * @param  string $form update/create/both
792
     */
793
    public function removeField($name, $form='both')
794
    {
795
        switch (strtolower($form)) {
796
            case 'create':
797
                array_forget($this->create_fields, $name);
798
                break;
799
800
            case 'update':
801
                array_forget($this->update_fields, $name);
802
                break;
803
804
            default:
805
                array_forget($this->create_fields, $name);
806
                array_forget($this->update_fields, $name);
807
                break;
808
        }
809
    }
810
811
    /**
812
     * Remove many fields from the create/update/both forms by their name.
813
     * @param  array $array_of_names A simple array of the names of the fields to be removed.
814
     * @param  string $form          update/create/both
815
     */
816
    public function removeFields($array_of_names, $form='both')
817
    {
818
        if (!empty($array_of_names)) {
819
            foreach ($array_of_names as $name) {
820
                $this->removeField($name, $form);
821
            }
822
        }
823
    }
824
825
    // TODO: $this->crud->replaceField('name', 'update/create/both');
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
826
827
    // TODO: $this->crud->setRequiredFields(['field_1', 'field_2'], 'update/create/both');
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...
828
    // TODO: $this->crud->setRequiredField('field_1', 'update/create/both');
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
829
    // TODO: $this->crud->getRequiredFields();
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...
830
831
    // TODO: $this->crud->setFieldOrder(['field_1', 'field_2', 'field_3'], 'update/create/both');
0 ignored issues
show
Unused Code Comprehensibility introduced by
66% 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...
832
833
834
    /**
835
     * Check if field is the first of its type in the given fields array.
836
     * 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).
837
     *
838
     * @param  array $field        The current field being tested if it's the first of its type.
839
     * @param  array $fields_array All the fields in that particular form.
840
     * @return bool  true/false
841
     */
842
    public function checkIfFieldIsFirstOfItsType($field, $fields_array) {
843
        if ($field['name'] == $this->getFirstOfItsTypeInArray($field['type'], $fields_array)['name'])
844
            return true;
845
846
        return false;
847
    }
848
849
850
    /**
851
     * Order the fields in a certain way.
852
     *
853
     * @param [string] Column name.
854
     * @param [attributes and values array]
855
     */
856
    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...
857
    {
858
        // TODO
859
    }
860
861
    // ALIAS of setFieldOrder($fields)
862
    public function setFieldsOrder($fields) { $this->setFieldOrder($fields); }
863
864
865
    // ----------------
866
    // ADVANCED QUERIES
867
    // ----------------
868
869
870
    /**
871
     * Add another clause to the query (for ex, a WHERE clause).
872
     *
873
     * Examples:
874
     * // $this->crud->addClause('active');
875
     * $this->crud->addClause('type', 'car');
876
     * $this->crud->addClause('where', 'name', '==', 'car');
877
     * $this->crud->addClause('whereName', 'car');
878
     * $this->crud->addClause('whereHas', 'posts', function($query) {
879
     *     $query->activePosts();
880
     *     });
881
     *
882
     * @param [type]
883
     */
884
    public function addClause($function)
885
    {
886
        return call_user_func_array([$this->query, $function], array_slice(func_get_args(), 1, 3));
887
    }
888
889
    /**
890
     * Order the results of the query in a certain way.
891
     *
892
     * @param  [type]
893
     * @param  string
894
     * @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...
895
     */
896
    public function orderBy($field, $order = 'asc')
897
    {
898
        return $this->query->orderBy($field, $order);
899
    }
900
901
    /**
902
     * Group the results of the query in a certain way.
903
     *
904
     * @param  [type]
905
     * @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...
906
     */
907
    public function groupBy($field)
908
    {
909
        return $this->query->groupBy($field);
910
    }
911
912
    /**
913
     * Limit the number of results in the query.
914
     *
915
     * @param  [number]
916
     * @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...
917
     */
918
    public function limit($number)
919
    {
920
        return $this->query->limit($number);
921
    }
922
923
924
925
    // ------------
926
    // BUTTONS
927
    // ------------
928
929
    // 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...
930
    // 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...
931
    // 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...
932
    // 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...
933
934
935
936
    // ------------------------------------------------------
937
    // AUTO-SET-FIELDS-AND-COLUMNS FUNCTIONALITY
938
    // ------------------------------------------------------
939
940
941
    /**
942
     * For a simple CRUD Panel, there should be no need to add/define the fields.
943
     * The public columns in the database will be converted to be fields.
944
     *
945
     */
946
    public function setFromDb()
947
    {
948
        $this->getDbColumnTypes();
949
950
        array_map(function($field) {
951
            // $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...
952
953
            $new_field =  [
954
                                'name' => $field,
955
                                'label' => ucfirst($field),
956
                                'value' => '', 'default' => $this->field_types[$field]['default'],
957
                                'type' => $this->getFieldTypeFromDbColumnType($field),
958
                                'values' => [],
959
                                'attributes' => []
960
                                ];
961
            $this->create_fields[] = $new_field;
962
            $this->update_fields[] = $new_field;
963
964
            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...
965
            {
966
                 $this->columns[] = [
967
                                    'name' => $field,
968
                                    'label' => ucfirst($field),
969
                                    'type' => $this->getFieldTypeFromDbColumnType($field)
970
                                    ];
971
            }
972
973
        }, $this->getDbColumnsNames());
974
    }
975
976
977
    /**
978
     * Get all columns from the database for that table.
979
     *
980
     * @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...
981
     */
982
    public function getDbColumnTypes()
983
    {
984
        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...
985
        {
986
            $this->field_types[$column->Field] = ['type' => trim(preg_replace('/\(\d+\)(.*)/i', '', $column->Type)), 'default' => $column->Default];
987
        }
988
989
        return $this->field_types;
990
    }
991
992
993
    /**
994
     * Intuit a field type, judging from the database column type.
995
     *
996
     * @param  [string] Field name.
997
     * @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...
998
     */
999
    public function getFieldTypeFromDbColumnType($field)
1000
    {
1001
        if (!array_key_exists($field, $this->field_types)) return 'text';
1002
1003
        if ($field == 'password') return 'password';
1004
1005
        if ($field == 'email') return 'email';
1006
1007
        switch ($this->field_types[$field]['type'])
1008
        {
1009
            case 'int':
1010
            case 'smallint':
1011
            case 'mediumint':
1012
            case 'longint':
1013
                return 'number';
1014
            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...
1015
1016
            case 'string':
1017
            case 'varchar':
1018
            case 'set':
1019
                return 'text';
1020
            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...
1021
1022
            // case 'enum':
1023
            //     return 'enum';
1024
            // break;
1025
1026
            case 'tinyint':
1027
                return 'active';
1028
            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...
1029
1030
            case 'text':
1031
            case 'mediumtext':
1032
            case 'longtext':
1033
                return 'textarea';
1034
            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...
1035
1036
            case 'date':
1037
                return 'date';
1038
            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...
1039
1040
            case 'datetime':
1041
            case 'timestamp':
1042
                return 'datetime';
1043
            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...
1044
            case 'time':
1045
                return 'time';
1046
            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...
1047
1048
            default:
1049
                return 'text';
1050
            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...
1051
        }
1052
    }
1053
1054
1055
    /**
1056
     * Turn a database column name or PHP variable into a pretty label to be shown to the user.
1057
     *
1058
     * @param  [string]
1059
     * @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...
1060
     */
1061
    public function makeLabel($value)
1062
    {
1063
        return trim(preg_replace('/(id|at|\[\])$/i', '', ucfirst(str_replace('_', ' ', $value))));
1064
    }
1065
1066
1067
    /**
1068
     * Get the database column names, in order to figure out what fields/columns to show in the auto-fields-and-columns functionality.
1069
     *
1070
     * @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...
1071
     */
1072
    public function getDbColumnsNames()
1073
    {
1074
        // Automatically-set columns should be both in the database, and in the $fillable variable on the Eloquent Model
1075
        $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...
1076
        $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...
1077
1078
        if (!empty($fillable)) $columns = array_intersect($columns, $fillable);
1079
1080
        // but not updated_at, deleted_at
1081
        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...
1082
    }
1083
1084
1085
1086
1087
1088
1089
1090
    // -----------------
1091
    // Commodity methods
1092
    // -----------------
1093
1094
    /**
1095
     * Refactor the request array to something that can be passed to the model's create or update function.
1096
     * The resulting array will only include the fields that are stored in the database and their values,
1097
     * plus the '_token' and 'redirect_after_save' variables.
1098
     *
1099
     * @param   Request     $request - everything that was sent from the form, usually \Request::all()
1100
     * @param   String      $form - create/update - to determine what fields should be compacted
1101
     * @return  array
1102
     */
1103
    public function compactFakeFields($request, $form = 'create')
1104
    {
1105
        $fake_field_columns_to_encode = [];
1106
1107
        // get the right fields according to the form type (create/update)
1108 View Code Duplication
        switch (strtolower($form)) {
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...
1109
            case 'update':
1110
                $fields = $this->update_fields;
1111
                break;
1112
1113
            default:
1114
                $fields = $this->create_fields;
1115
                break;
1116
        }
1117
1118
        // go through each defined field
1119
        foreach ($fields as $k => $field) {
1120
            // if it's a fake field
1121
            if (isset($fields[$k]['fake']) && $fields[$k]['fake'] == true) {
1122
                // add it to the request in its appropriate variable - the one defined, if defined
1123
                if (isset($fields[$k]['store_in'])) {
1124
                    $request[$fields[$k]['store_in']][$fields[$k]['name']] = $request[$fields[$k]['name']];
1125
1126
                    $remove_fake_field = array_pull($request, $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...
1127 View Code Duplication
                    if (!in_array($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...
1128
                        array_push($fake_field_columns_to_encode, $fields[$k]['store_in']);
1129
                    }
1130
                } else //otherwise in the one defined in the $crud variable
1131
                {
1132
                    $request['extras'][$fields[$k]['name']] = $request[$fields[$k]['name']];
1133
1134
                    $remove_fake_field = array_pull($request, $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...
1135
                    if (!in_array('extras', $fake_field_columns_to_encode, true)) {
1136
                        array_push($fake_field_columns_to_encode, 'extras');
1137
                    }
1138
                }
1139
            }
1140
        }
1141
1142
        // json_encode all fake_value columns in the database, so they can be properly stored and interpreted
1143
        if (count($fake_field_columns_to_encode)) {
1144
            foreach ($fake_field_columns_to_encode as $key => $value) {
1145
                $request[$value] = json_encode($request[$value]);
1146
            }
1147
        }
1148
1149
        // if there are no fake fields defined, this will just return the original Request in full
1150
        // since no modifications or additions have been made to $request
1151
        return $request;
1152
    }
1153
1154
1155
    /**
1156
     * Returns an array of database columns names, that are used to store fake values.
1157
     * Returns ['extras'] if no columns have been found.
1158
     *
1159
     */
1160
    public function getFakeColumnsAsArray($form = 'create')
1161
    {
1162
        $fake_field_columns_to_encode = [];
1163
1164
        // get the right fields according to the form type (create/update)
1165 View Code Duplication
        switch (strtolower($form)) {
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...
1166
            case 'update':
1167
                $fields = $this->update_fields;
1168
                break;
1169
1170
            default:
1171
                $fields = $this->create_fields;
1172
                break;
1173
        }
1174
1175
1176
        foreach ($fields as $k => $field) {
1177
            // if it's a fake field
1178
            if (isset($fields[$k]['fake']) && $fields[$k]['fake'] == true) {
1179
                // add it to the request in its appropriate variable - the one defined, if defined
1180
                if (isset($fields[$k]['store_in'])) {
1181 View Code Duplication
                    if (!in_array($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...
1182
                        array_push($fake_field_columns_to_encode, $fields[$k]['store_in']);
1183
                    }
1184
                } else //otherwise in the one defined in the $crud variable
1185
                {
1186
                    if (!in_array('extras', $fake_field_columns_to_encode, true)) {
1187
                        array_push($fake_field_columns_to_encode, 'extras');
1188
                    }
1189
                }
1190
            }
1191
        }
1192
1193
        if (!count($fake_field_columns_to_encode)) {
1194
            return ['extras'];
1195
        }
1196
1197
        return $fake_field_columns_to_encode;
1198
    }
1199
1200
1201
1202
1203
1204
1205
1206
1207
    // ----------------------------------
1208
    // Miscellaneous functions or methods
1209
    // ----------------------------------
1210
1211
1212
    /**
1213
     * Return the first element in an array that has the given 'type' attribute.
1214
     * @param  string $type
1215
     * @param  array $array
1216
     * @return array
1217
     */
1218
    public function getFirstOfItsTypeInArray($type, $array)
1219
    {
1220
        return array_first($array, function($key, $item) use ($type) {
1221
            return $item['type'] == $type;
1222
        });
1223
    }
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
    // ------------
1236
    // TONE FUNCTIONS - UNDOCUMENTED, UNTESTED, SOME MAY BE USED IN THIS FILE
1237
    // ------------
1238
    //
1239
    // TODO:
1240
    // - figure out if they are really needed
1241
    // - comments inside the function to explain how they work
1242
    // - write docblock for them
1243
    // - place in the correct section above (CREATE, READ, UPDATE, DELETE, ACCESS, MANIPULATION)
1244
1245
1246
1247
    public function addButton($button)
1248
    {
1249
        array_unshift($this->buttons, $button);
1250
    }
1251
1252
    public function buttons()
1253
    {
1254
        return $this->buttons;
1255
    }
1256
1257
    public function addCustomButton($button)
1258
    {
1259
        array_unshift($this->custom_buttons, $button);
1260
    }
1261
1262
    public function customButtons()
1263
    {
1264
        return $this->custom_buttons;
1265
    }
1266
1267
    public function showButtons()
1268
    {
1269
        return !empty($this->buttons) && !(count($this->buttons) == 1 && array_key_exists('add', $this->buttons));
1270
    }
1271
1272
    public function initButtons()
1273
    {
1274
        $this->buttons = [
1275
            'add' => ['route' => "{$this->route}/create", 'label' => trans('crud::crud.buttons.add'), 'class' => '', 'hide' => [], 'icon' => 'fa-plus-circle', 'extra' => []],
1276
            'view' => ['route' => "{$this->route}/%d", 'label' => trans('crud::crud.buttons.view'), 'class' => '', 'hide' => [], 'icon' => 'fa-eye', 'extra' => []],
1277
            'edit' => ['route' => "{$this->route}/%d/edit", 'label' => trans('crud::crud.buttons.edit'), 'class' => '', 'hide' => [], 'icon' => 'fa-edit', 'extra' => []],
1278
            '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']],
1279
        ];
1280
    }
1281
1282
    public function removeButtons($buttons)
1283
    {
1284
        foreach ($buttons as $button)
1285
        {
1286
            unset($this->buttons[$button]);
1287
        }
1288
1289
        return $this->buttons;
1290
    }
1291
1292
1293
1294
1295
1296
1297
1298
1299
    public function getColumns()
1300
    {
1301
        return $this->sort('columns');
1302
    }
1303
1304
    public function orderColumns($order)
1305
    {
1306
        $this->setSort('columns', (array)$order);
1307
    }
1308
1309
1310
1311
1312
1313
1314
    public function setFields($fields)
1315
    {
1316
        $this->addMultiple('fields', $fields);
1317
    }
1318
1319
    // [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...
1320
    // public function addField($field)
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% 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...
1321
    // {
1322
    //     return $this->add('fields', $field);
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% 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...
1323
    // }
1324
1325
    public function updateFields($fields, $attributes)
1326
    {
1327
        $this->sync('fields', $fields, $attributes);
1328
    }
1329
1330
    // public function removeFields($fields)
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% 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...
1331
    // {
1332
    //     $this->fields = $this->remove('fields', $fields);
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% 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...
1333
    //     $this->removeColumns($fields);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% 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...
1334
    // }
1335
1336
    public function setCreateFields($fields)
1337
    {
1338
        $this->addMultiple('create_fields', $fields);
1339
    }
1340
1341
    public function addCreateField($field)
1342
    {
1343
       return $this->add('create_fields', $field);
0 ignored issues
show
Bug introduced by
The method add() does not seem to exist on object<Backpack\CRUD\Crud>.

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...
1344
    }
1345
1346
     public function setUpdateFields($fields)
1347
    {
1348
        $this->addMultiple('update_fields', $fields);
1349
    }
1350
1351
    public function addUpdateField($field)
1352
    {
1353
        return $this->add('update_fields', $field);
0 ignored issues
show
Bug introduced by
The method add() does not seem to exist on object<Backpack\CRUD\Crud>.

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...
1354
    }
1355
1356
    public function fields()
1357
    {
1358
        if (!$this->entry && !empty($this->create_fields))
1359
        {
1360
            $this->syncRelations('create_fields');
1361
1362
            return $this->create_fields;
1363
        }
1364
1365
        if ($this->entry && !empty($this->update_fields))
1366
        {
1367
            $this->syncRelations('update_fields');
1368
            $this->addFieldsValue();
1369
1370
            return $this->update_fields;
1371
        }
1372
1373
        $this->syncRelations('fields');
1374
        $this->addFieldsValue();
1375
1376
        return $this->sort('fields');
1377
    }
1378
1379
    public function orderFields($order)
1380
    {
1381
        $this->setSort('fields', (array)$order);
1382
    }
1383
1384
1385
    // public function syncField($field)
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% 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...
1386
    // {
1387
    //     if (array_key_exists('name', (array)$field))
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% 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...
1388
    //         return array_merge(['type' => $this->getFieldTypeFromDbColumnType($field['name']), 'value' => '', 'default' => null, 'values' => [], 'attributes' => []], $field);
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% 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...
1389
1390
    //     return false;
1391
    // }
1392
1393
1394
1395
1396
1397
    // iti pune valorile pe field-uri la EDIT
1398
    public function addFieldsValue()
1399
    {
1400
        if ($this->entry)
1401
        {
1402
            $fields = !empty($this->update_fields) ? 'update_fields' : 'fields';
1403
1404
            foreach ($this->{$fields} as $key => $field)
1405
            {
1406
                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();
1407
                    else $this->{$fields}[$key]['value'] = $this->entry->{$field['name']};
1408
            }
1409
        }
1410
    }
1411
1412
    // public function add($entity, $field)
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% 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...
1413
    // {
1414
    //     return array_filter($this->{$entity}[] = $this->syncField($field));
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% 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...
1415
    // }
1416
1417
    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...
1418
    {
1419
        $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...
1420
    }
1421
1422
    public function sync($type, $fields, $attributes)
1423
    {
1424
        if (!empty($this->{$type}))
1425
        {
1426
            $this->{$type} = array_map(function($field) use ($fields, $attributes) {
1427
                if (in_array($field['name'], (array)$fields)) $field = array_merge($field, $attributes);
1428
1429
                return $field;
1430
            }, $this->{$type});
1431
        }
1432
    }
1433
1434
1435
1436
    // public function remove($entity, $fields)
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% 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...
1437
    // {
1438
    //     return array_values(array_filter($this->{$entity}, function($field) use ($fields) { return !in_array($field['name'], (array)$fields);}));
0 ignored issues
show
Unused Code Comprehensibility introduced by
74% 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...
1439
    // }
1440
1441
    public function setSort($items, $order)
1442
    {
1443
        $this->sort[$items] = $order;
1444
    }
1445
1446
    public function sort($items)
1447
    {
1448
        if (array_key_exists($items, $this->sort))
1449
        {
1450
            $elements = [];
1451
1452
            foreach ($this->sort[$items] as $item)
1453
            {
1454
                if (is_numeric($key = array_search($item, array_column($this->{$items}, 'name')))) $elements[] = $this->{$items}[$key];
1455
            }
1456
1457
            return $this->{$items} = array_merge($elements, array_filter($this->{$items}, function($item) use($items) {return !in_array($item['name'], $this->sort[$items]);}));
1458
        }
1459
1460
        return $this->{$items};
1461
    }
1462
1463
1464
1465
1466
1467
    // cred ca ia valorile din tabela de legatura ca sa ti le afiseze in select
1468
    public function getRelationValues($model, $field, $where = [], $order = [])
1469
    {
1470
        $order = (array)$order;
1471
        $values = $model->select('*');
1472
1473
        if (!empty($where)) call_user_func_array([$values, $where[0]], array_slice($where, 1));
1474
1475
        if (!empty($order)) call_user_func_array([$values, 'orderBy'], $order);
1476
1477
        return $values->get()->lists($field, $model->getKeyName())->toArray();
1478
    }
1479
1480
    // face un fel de merge intre ce ii dai si ce e in CRUD
1481
    public function syncRelations($entity)
1482
    {
1483
        foreach ($this->relations as $field => $relation) {
1484
            if ($relation['pivot']) $this->add($entity, ['name' => $field, 'type' => 'multiselect', 'value' => [], 'values' => $this->relations[$field]['values']]);
0 ignored issues
show
Bug introduced by
The method add() does not seem to exist on object<Backpack\CRUD\Crud>.

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...
1485
                else $this->sync($entity, $field, ['type' => 'select', 'values' => $this->relations[$field]['values']]);
1486
        }
1487
    }
1488
1489
1490
1491
}