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 ( 0b5ddf...759348 )
by Cristian
04:01
created

Crud::checkIfFieldIsFirstOfItsType()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 6
rs 9.4285
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']) || isset($field['dependencies'])){
106
                array_push($relationFields, $field);
107
            }
108
        }
109
110
        return $relationFields;
111
    }
112
113
114
    public function syncPivot($model, $data, $form = 'create')
115
    {
116
117
        $relations = $this->getRelationFields($form);
118
119
        foreach ($relations as $key => $relation)
120
        {
121
            if ( (isset($relation['pivot']) && $relation['pivot'] ) || isset($relation['dependencies']) ){
122
                if(is_array($relation['name'])){
123
                    foreach($relation['name'] as $relation){
124
                        if(isset($data[$relation])){
125
                            $model->{$relation}()->sync($data[$relation]);
126
                        }else{
127
                             $model->{$relation}()->sync([]);
128
                        }
129
                    }
130
                }else{
131
                    $model->{$relation['name']}()->sync($data[$relation['name']]);
132
                }
133
134
                if( isset($relation['pivotFields']) ){
135
                    foreach($relation['pivotFields'] as $pivotField){
136
                       foreach($data[$pivotField] as $pivot_id =>  $field){
137
                         $model->{$relation['name']}()->updateExistingPivot($pivot_id, [$pivotField => $field]);
138
                       }
139
                    }
140
                }
141
            }
142
        }
143
    }
144
145
146
147
    /**
148
     * Adds a required => true attribute to each field, so that the required asterisc will show up in the create/update forms.
149
     * TODO: make this work, by editing the $this->fields variable and all fields.
150
     *
151
     * @param [string or array of strings]
152
     */
153
    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...
154
    {
155
        // TODO
156
    }
157
158
    /**
159
     * Adds a required => true attribute to this field, so that the required asteris will show up in the create/update forms.
160
     *
161
     * @param [string]
162
     */
163
    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...
164
    {
165
        // TODO
166
    }
167
168
    /**
169
     * Get all fields that have the required attribute.
170
     * TODO: make this work after making setRequiredFields() work.
171
     *
172
     * @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...
173
     */
174
    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...
175
    {
176
        // TODO
177
    }
178
179
180
   /*
181
    |--------------------------------------------------------------------------
182
    |                                   READ
183
    |--------------------------------------------------------------------------
184
    */
185
186
    /**
187
     * Find and retrieve an entry in the database or fail.
188
     *
189
     * @param  [int] The id of the row in the db to fetch.
190
     * @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...
191
     */
192
    public function getEntry($id)
193
    {
194
        $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...
195
        return $entry->withFakes();
196
    }
197
198
199
    /**
200
     * Get all entries from the database.
201
     *
202
     * @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...
203
     */
204
    public function getEntries()
205
    {
206
        $entries = $this->query->get();
207
208
        // add the fake columns for each entry
209
        foreach ($entries as $key => $entry) {
210
            $entry->addFakes($this->getFakeColumnsAsArray());
211
        }
212
213
        return $entries;
214
    }
215
216
217
    /**
218
     * Get the fields for the create or update forms.
219
     *
220
     * @param  [form] create / update / both - defaults to 'both'
221
     * @param  [integer] the ID of the entity to be edited in the Update form
222
     * @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...
223
     */
224
    public function getFields($form, $id = false)
225
    {
226
        switch (strtolower($form)) {
227
            case 'create':
228
                return $this->getCreateFields();
229
                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...
230
231
            case 'update':
232
                return $this->getUpdateFields($id);
233
                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...
234
235
            default:
236
                return $this->getCreateFields();
237
                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...
238
        }
239
    }
240
241
    /**
242
     * Enable the DETAILS ROW functionality:
243
     *
244
     * In the table view, show a plus sign next to each entry.
245
     * 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.
246
     */
247
    public function enableDetailsRow()
248
    {
249
        $this->details_row = true;
250
    }
251
252
    /**
253
     * Disable the DETAILS ROW functionality:
254
     */
255
    public function disableDetailsRow()
256
    {
257
        $this->details_row = false;
258
    }
259
260
261
262
   /*
263
    |--------------------------------------------------------------------------
264
    |                                   UPDATE
265
    |--------------------------------------------------------------------------
266
    */
267
268
    /**
269
     * Update a row in the database.
270
     *
271
     * @param  [Int] The entity's id
272
     * @param  [Request] All inputs to be updated.
273
     * @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...
274
     */
275
    public function update($id, $data)
276
    {
277
        $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...
278
        $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...
279
280
        /*if ($updated) */$this->syncPivot($item, $data, 'update');
281
282
        return $item;
283
    }
284
285
286
    /**
287
     * Get all fields needed for the EDIT ENTRY form.
288
     *
289
     * @param  [integer] The id of the entry that is being edited.
290
     * @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...
291
     */
292
    public function getUpdateFields($id)
293
    {
294
        $fields = $this->update_fields;
295
        $entry = $this->getEntry($id);
296
297
        foreach ($fields as $k => $field) {
298
            // set the value
299
            if (!isset($fields[$k]['value']))
300
            {
301
                if(is_array($field['name'])){
302
303
                    $fields[$k]['value'] = [];
304
                    foreach($field['name'] as  $key => $relation){
305
                        $fields[$k]['value'][] = $entry->{$relation};
306
                    }
307
308
                }else{
309
                    $fields[$k]['value'] = $entry->{$field['name']};
310
                }
311
            }
312
        }
313
314
        // always have a hidden input for the entry id
315
        $fields['id'] = array(
316
                        'name' => 'id',
317
                        'value' => $entry->id,
318
                        'type' => 'hidden'
319
                    );
320
321
        return $fields;
322
    }
323
324
325
326
327
   /*
328
    |--------------------------------------------------------------------------
329
    |                                   DELETE
330
    |--------------------------------------------------------------------------
331
    */
332
333
    /**
334
     * Delete a row from the database.
335
     *
336
     * @param  [int] The id of the item to be deleted.
337
     * @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...
338
     *
339
     * TODO: should this delete items with relations to it too?
340
     */
341
    public function delete($id)
342
    {
343
        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...
344
    }
345
346
347
348
349
    /*
350
    |--------------------------------------------------------------------------
351
    |                                   REORDER
352
    |--------------------------------------------------------------------------
353
    */
354
355
356
    /**
357
     * Change the order and parents of the given elements, according to the NestedSortable AJAX call.
358
     *
359
     * @param  [Request] The entire request from the NestedSortable AJAX Call.
360
     * @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...
361
     */
362
    public function updateTreeOrder($request)
363
    {
364
        $count = 0;
365
366
        foreach ($request as $key => $entry) {
367
            if ($entry['item_id'] != "" && $entry['item_id'] != null) {
368
                $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...
369
                $item->parent_id = $entry['parent_id'];
370
                $item->depth = $entry['depth'];
371
                $item->lft = $entry['left'];
372
                $item->rgt = $entry['right'];
373
                $item->save();
374
375
                $count++;
376
            }
377
        }
378
379
        return $count;
380
    }
381
382
383
    /**
384
     * Enable the Reorder functionality in the CRUD Panel for users that have the been given access to 'reorder' using:
385
     * $this->crud->allowAccess('reorder');
386
     *
387
     * @param  [string] Column name that will be shown on the labels.
388
     * @param  [integer] Maximum hierarchy level to which the elements can be nested (1 = no nesting, just reordering).
389
     */
390
    public function enableReorder($label = 'name', $max_level = 1)
391
    {
392
        $this->reorder = true;
393
        $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...
394
        $this->reorder_max_level = $max_level;
395
    }
396
397
    /**
398
     * Disable the Reorder functionality in the CRUD Panel for all users.
399
     *
400
     */
401
    public function disableReorder()
402
    {
403
        $this->reorder = false;
404
    }
405
406
    /**
407
     * Check if the Reorder functionality is enabled or not.
408
     *
409
     * @return boolean
410
     */
411
    public function isReorderEnabled()
412
    {
413
        return $this->reorder;
414
    }
415
416
417
418
   /*
419
    |--------------------------------------------------------------------------
420
    |                                   CRUD ACCESS
421
    |--------------------------------------------------------------------------
422
    */
423
424
    public function allowAccess($access)
425
    {
426
        // $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...
427
        return $this->access = array_merge(array_diff((array)$access, $this->access), $this->access);
428
    }
429
430
    public function denyAccess($access)
431
    {
432
        // $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...
433
        return $this->access = array_diff($this->access, (array)$access);
434
    }
435
436
    /**
437
     * Check if a permission is enabled for a Crud Panel. Return false if not.
438
     *
439
     * @param  [string] Permission.
440
     * @return boolean
441
     */
442
    public function hasAccess($permission)
443
    {
444
        if (!in_array($permission, $this->access))
445
        {
446
            return false;
447
        }
448
        return true;
449
    }
450
451
    /**
452
     * Check if a permission is enabled for a Crud Panel. Fail if not.
453
     *
454
     * @param  [string] Permission.
455
     * @return boolean
456
     */
457
    public function hasAccessOrFail($permission)
458
    {
459
        if (!in_array($permission, $this->access))
460
        {
461
            abort(403, trans('backpack::crud.unauthorized_access'));
462
        }
463
    }
464
465
466
467
    /*
468
    |--------------------------------------------------------------------------
469
    |                               CRUD MANIPULATION
470
    |--------------------------------------------------------------------------
471
    */
472
473
474
475
    // ------------------------------------------------------
476
    // BASICS - model, route, entity_name, entity_name_plural
477
    // ------------------------------------------------------
478
479
    /**
480
     * This function binds the CRUD to its corresponding Model (which extends Eloquent).
481
     * All Create-Read-Update-Delete operations are done using that Eloquent Collection.
482
     *
483
     * @param [string] Full model namespace. Ex: App\Models\Article
484
     */
485
    public function setModel($model_namespace)
486
    {
487
        if (!class_exists($model_namespace)) throw new \Exception('This model does not exist.', 404);
488
489
        $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...
490
        $this->query = $this->model->select('*');
491
492
        // $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...
493
    }
494
495
    /**
496
     * Get the corresponding Eloquent Model for the CrudController, as defined with the setModel() function;
497
     *
498
     * @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...
499
     */
500
    public function getModel()
501
    {
502
        return $this->model;
503
    }
504
505
    /**
506
     * Set the route for this CRUD.
507
     * Ex: admin/article
508
     *
509
     * @param [string] Route name.
510
     * @param [array] Parameters.
511
     */
512
    public function setRoute($route)
513
    {
514
        $this->route = $route;
515
        $this->initButtons();
516
    }
517
518
    /**
519
     * Set the route for this CRUD using the route name.
520
     * Ex: admin.article
521
     *
522
     * @param [string] Route name.
523
     * @param [array] Parameters.
524
     */
525
    public function setRouteName($route, $parameters = [])
526
    {
527
        $complete_route = $route.'.index';
528
529
        if (!\Route::has($complete_route)) throw new \Exception('There are no routes for this route name.', 404);
530
531
        $this->route = route($complete_route, $parameters);
532
        $this->initButtons();
533
    }
534
535
    /**
536
     * Get the current CrudController route.
537
     *
538
     * Can be defined in the CrudController with:
539
     * - $this->crud->setRoute('admin/article')
540
     * - $this->crud->setRouteName('admin.article')
541
     * - $this->crud->route = "admin/article"
542
     *
543
     * @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...
544
     */
545
    public function getRoute()
546
    {
547
        return $this->route;
548
    }
549
550
    /**
551
     * Set the entity name in singular and plural.
552
     * Used all over the CRUD interface (header, add button, reorder button, breadcrumbs).
553
     *
554
     * @param [string] Entity name, in singular. Ex: article
555
     * @param [string] Entity name, in plural. Ex: articles
556
     */
557
    public function setEntityNameStrings($singular, $plural) {
558
        $this->entity_name = $singular;
559
        $this->entity_name_plural = $plural;
560
    }
561
562
563
564
565
    // ------------
566
    // COLUMNS
567
    // ------------
568
569
    /**
570
     * Add a bunch of column names and their details to the CRUD object.
571
     *
572
     * @param [array or multi-dimensional array]
573
     */
574
    public function setColumns($columns)
575
    {
576
        // clear any columns already set
577
        $this->columns = [];
578
579
        // if array, add a column for each of the items
580
        if (is_array($columns) && count($columns)) {
581
            foreach ($columns as $key => $column) {
582
                // if label and other details have been defined in the array
583
                if (is_array($columns[0])) {
584
                    $this->addColumn($column);
585
                }
586
                else
587
                {
588
                    $this->addColumn([
589
                                    'name' => $column,
590
                                    'label' => ucfirst($column),
591
                                    'type' => 'text'
592
                                ]);
593
                }
594
            }
595
        }
596
597
        if (is_string($columns)) {
598
            $this->addColumn([
599
                                'name' => $columns,
600
                                'label' => ucfirst($columns),
601
                                'type' => 'text'
602
                                ]);
603
        }
604
605
        // This was the old setColumns() function, and it did not work:
606
        // $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...
607
    }
608
609
    /**
610
     * Add a column at the end of to the CRUD object's "columns" array.
611
     *
612
     * @param [string or array]
613
     */
614
    public function addColumn($column)
615
    {
616
        // make sure the column has a type
617
        $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...
618
619
        // make sure the column has a label
620
        $column_with_details = $this->addDefaultLabel($column);
621
622
        return array_filter($this->columns[] = $column_with_details);
623
    }
624
625
    /**
626
     * Add multiple columns at the end of the CRUD object's "columns" array.
627
     *
628
     * @param [array of columns]
629
     */
630
    public function addColumns($columns)
631
    {
632
        if (count($columns)) {
633
            foreach ($columns as $key => $column) {
634
                $this->addColumn($column);
635
            }
636
        }
637
    }
638
639
    /**
640
     * Add the default column type to the given Column, inferring the type from the database column type.
641
     *
642
     * @param [column array]
643
     */
644
    public function addDefaultTypeToColumn($column)
645
    {
646
        if (array_key_exists('name', (array)$column))
647
        {
648
            $default_type = $this->getFieldTypeFromDbColumnType($column['name']);
649
            return array_merge(['type' => $default_type], $column);
650
        }
651
652
        return false;
653
    }
654
655
    /**
656
     * If a field or column array is missing the "label" attribute, an ugly error would be show.
657
     * So we add the field Name as a label - it's better than nothing.
658
     *
659
     * @param [field or column]
660
     */
661
    public function addDefaultLabel($array) {
662
        if (!array_key_exists('label', (array)$array) && array_key_exists('name', (array)$array)) {
663
            $array = array_merge(['label' => ucfirst($this->makeLabel($array['name']))], $array);
664
            return $array;
665
        }
666
667
        return $array;
668
    }
669
670
    /**
671
     * Remove multiple columns from the CRUD object using their names.
672
     *
673
     * @param  [column array]
674
     */
675
    public function removeColumns($columns)
676
    {
677
        $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...
678
    }
679
680
    /**
681
     * Remove a column from the CRUD object using its name.
682
     *
683
     * @param  [column array]
684
     */
685
    public function removeColumn($column)
686
    {
687
        return $this->removeColumns([$column]);
688
    }
689
690
    /**
691
     * Change attributes for multiple columns.
692
     *
693
     * @param [columns arrays]
694
     * @param [attributes and values array]
695
     */
696
    public function setColumnsDetails($columns, $attributes)
697
    {
698
        $this->sync('columns', $columns, $attributes);
699
    }
700
701
    /**
702
     * Change attributes for a certain column.
703
     *
704
     * @param [string] Column name.
705
     * @param [attributes and values array]
706
     */
707
    public function setColumnDetails($column, $attributes)
708
    {
709
        $this->setColumnsDetails([$column], $attributes);
710
    }
711
712
713
    /**
714
     * Order the columns in a certain way.
715
     *
716
     * @param [string] Column name.
717
     * @param [attributes and values array]
718
     */
719
    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...
720
    {
721
        // TODO
722
    }
723
724
    // ALIAS of setColumnOrder($columns)
725
    public function setColumnsOrder($columns) { $this->setColumnOrder($columns); }
726
727
728
    // ------------
729
    // FIELDS
730
    // ------------
731
732
    /**
733
     * Add a field to the create/update form or both.
734
     * @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...
735
     * @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...
736
     * @param string $form    The form to add the field to (create/update/both)
737
     */
738
    public function addField($field, $form='both')
739
    {
740
        // if the field_defition_array array is a string, it means the programmer was lazy and has only passed the name
741
        // set some default values, so the field will still work
742
        if (is_string($field))
743
        {
744
            $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...
745
        }
746
        else
747
        {
748
            $complete_field_array = $field;
749
        }
750
751
        // if the label is missing, we should set it
752
        if (!isset($complete_field_array['label']))
753
            $complete_field_array['label'] = ucfirst($complete_field_array['name']);
754
755
        // if the field type is missing, we should set it
756
        if (!isset($complete_field_array['type']))
757
            $complete_field_array['type'] = $this->getFieldTypeFromDbColumnType($complete_field_array['name']);
758
759
        // store the field information into the correct variable on the CRUD object
760
        switch (strtolower($form)) {
761
            case 'create':
762
                $this->create_fields[$complete_field_array['name']] = $complete_field_array;
763
                break;
764
765
            case 'update':
766
                $this->update_fields[$complete_field_array['name']] = $complete_field_array;
767
                break;
768
769
            default:
770
                $this->create_fields[$complete_field_array['name']] = $complete_field_array;
771
                $this->update_fields[$complete_field_array['name']] = $complete_field_array;
772
                break;
773
        }
774
    }
775
776
    /**
777
     * Remove a certain field from the create/update/both forms by its name.
778
     * @param  string $name Field name (as defined with the addField() procedure)
779
     * @param  string $form update/create/both
780
     */
781
    public function removeField($name, $form='both')
782
    {
783
        switch (strtolower($form)) {
784
            case 'create':
785
                array_forget($this->create_fields, $name);
786
                break;
787
788
            case 'update':
789
                array_forget($this->update_fields, $name);
790
                break;
791
792
            default:
793
                array_forget($this->create_fields, $name);
794
                array_forget($this->update_fields, $name);
795
                break;
796
        }
797
    }
798
799
    /**
800
     * Remove many fields from the create/update/both forms by their name.
801
     * @param  array $array_of_names A simple array of the names of the fields to be removed.
802
     * @param  string $form          update/create/both
803
     */
804
    public function removeFields($array_of_names, $form='both')
805
    {
806
        if (!empty($array_of_names)) {
807
            foreach ($array_of_names as $name) {
808
                $this->removeField($name, $form);
809
            }
810
        }
811
    }
812
813
    // 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...
814
815
    // 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...
816
    // 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...
817
    // 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...
818
819
    // 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...
820
821
822
    /**
823
     * Check if field is the first of its type in the given fields array.
824
     * 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).
825
     *
826
     * @param  array $field        The current field being tested if it's the first of its type.
827
     * @param  array $fields_array All the fields in that particular form.
828
     * @return bool  true/false
829
     */
830
    public function checkIfFieldIsFirstOfItsType($field, $fields_array) {
831
        if ($field['name'] == $this->getFirstOfItsTypeInArray($field['type'], $fields_array)['name'])
832
            return true;
833
834
        return false;
835
    }
836
837
838
    /**
839
     * Order the fields in a certain way.
840
     *
841
     * @param [string] Column name.
842
     * @param [attributes and values array]
843
     */
844
    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...
845
    {
846
        // TODO
847
    }
848
849
    // ALIAS of setFieldOrder($fields)
850
    public function setFieldsOrder($fields) { $this->setFieldOrder($fields); }
851
852
853
    // ----------------
854
    // ADVANCED QUERIES
855
    // ----------------
856
857
858
    /**
859
     * Add another clause to the query (for ex, a WHERE clause).
860
     *
861
     * Examples:
862
     * // $this->crud->addClause('active');
863
     * $this->crud->addClause('type', 'car');
864
     * $this->crud->addClause('where', 'name', '==', 'car');
865
     * $this->crud->addClause('whereName', 'car');
866
     * $this->crud->addClause('whereHas', 'posts', function($query) {
867
     *     $query->activePosts();
868
     *     });
869
     *
870
     * @param [type]
871
     */
872
    public function addClause($function)
873
    {
874
        return call_user_func_array([$this->query, $function], array_slice(func_get_args(), 1, 3));
875
    }
876
877
    /**
878
     * Order the results of the query in a certain way.
879
     *
880
     * @param  [type]
881
     * @param  string
882
     * @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...
883
     */
884
    public function orderBy($field, $order = 'asc')
885
    {
886
        return $this->query->orderBy($field, $order);
887
    }
888
889
    /**
890
     * Group the results of the query in a certain way.
891
     *
892
     * @param  [type]
893
     * @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...
894
     */
895
    public function groupBy($field)
896
    {
897
        return $this->query->groupBy($field);
898
    }
899
900
    /**
901
     * Limit the number of results in the query.
902
     *
903
     * @param  [number]
904
     * @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...
905
     */
906
    public function limit($number)
907
    {
908
        return $this->query->limit($number);
909
    }
910
911
912
913
    // ------------
914
    // BUTTONS
915
    // ------------
916
917
    // 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...
918
    // 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...
919
    // 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...
920
    // 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...
921
922
923
924
    // ------------------------------------------------------
925
    // AUTO-SET-FIELDS-AND-COLUMNS FUNCTIONALITY
926
    // ------------------------------------------------------
927
928
929
    /**
930
     * For a simple CRUD Panel, there should be no need to add/define the fields.
931
     * The public columns in the database will be converted to be fields.
932
     *
933
     */
934
    public function setFromDb()
935
    {
936
        $this->getDbColumnTypes();
937
938
        array_map(function($field) {
939
            // $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...
940
941
            $new_field =  [
942
                                'name' => $field,
943
                                'label' => ucfirst($field),
944
                                'value' => '', 'default' => $this->field_types[$field]['default'],
945
                                'type' => $this->getFieldTypeFromDbColumnType($field),
946
                                'values' => [],
947
                                'attributes' => []
948
                                ];
949
            $this->create_fields[] = $new_field;
950
            $this->update_fields[] = $new_field;
951
952
            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...
953
            {
954
                 $this->columns[] = [
955
                                    'name' => $field,
956
                                    'label' => ucfirst($field),
957
                                    'type' => $this->getFieldTypeFromDbColumnType($field)
958
                                    ];
959
            }
960
961
        }, $this->getDbColumnsNames());
962
    }
963
964
965
    /**
966
     * Get all columns from the database for that table.
967
     *
968
     * @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...
969
     */
970
    public function getDbColumnTypes()
971
    {
972
        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...
973
        {
974
            $this->field_types[$column->Field] = ['type' => trim(preg_replace('/\(\d+\)(.*)/i', '', $column->Type)), 'default' => $column->Default];
975
        }
976
977
        return $this->field_types;
978
    }
979
980
981
    /**
982
     * Intuit a field type, judging from the database column type.
983
     *
984
     * @param  [string] Field name.
985
     * @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...
986
     */
987
    public function getFieldTypeFromDbColumnType($field)
988
    {
989
        if (!array_key_exists($field, $this->field_types)) return 'text';
990
991
        if ($field == 'password') return 'password';
992
993
        if ($field == 'email') return 'email';
994
995
        switch ($this->field_types[$field]['type'])
996
        {
997
            case 'int':
998
            case 'smallint':
999
            case 'mediumint':
1000
            case 'longint':
1001
                return 'number';
1002
            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...
1003
1004
            case 'string':
1005
            case 'varchar':
1006
            case 'set':
1007
                return 'text';
1008
            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...
1009
1010
            // case 'enum':
1011
            //     return 'enum';
1012
            // break;
1013
1014
            case 'tinyint':
1015
                return 'active';
1016
            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...
1017
1018
            case 'text':
1019
            case 'mediumtext':
1020
            case 'longtext':
1021
                return 'textarea';
1022
            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...
1023
1024
            case 'date':
1025
                return 'date';
1026
            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...
1027
1028
            case 'datetime':
1029
            case 'timestamp':
1030
                return 'datetime';
1031
            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...
1032
            case 'time':
1033
                return 'time';
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
            default:
1037
                return 'text';
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
    }
1041
1042
1043
    /**
1044
     * Turn a database column name or PHP variable into a pretty label to be shown to the user.
1045
     *
1046
     * @param  [string]
1047
     * @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...
1048
     */
1049
    public function makeLabel($value)
1050
    {
1051
        return trim(preg_replace('/(id|at|\[\])$/i', '', ucfirst(str_replace('_', ' ', $value))));
1052
    }
1053
1054
1055
    /**
1056
     * Get the database column names, in order to figure out what fields/columns to show in the auto-fields-and-columns functionality.
1057
     *
1058
     * @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...
1059
     */
1060
    public function getDbColumnsNames()
1061
    {
1062
        // Automatically-set columns should be both in the database, and in the $fillable variable on the Eloquent Model
1063
        $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...
1064
        $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...
1065
1066
        if (!empty($fillable)) $columns = array_intersect($columns, $fillable);
1067
1068
        // but not updated_at, deleted_at
1069
        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...
1070
    }
1071
1072
1073
1074
1075
1076
1077
1078
    // -----------------
1079
    // Commodity methods
1080
    // -----------------
1081
1082
    /**
1083
     * Refactor the request array to something that can be passed to the model's create or update function.
1084
     * The resulting array will only include the fields that are stored in the database and their values,
1085
     * plus the '_token' and 'redirect_after_save' variables.
1086
     *
1087
     * @param   Request     $request - everything that was sent from the form, usually \Request::all()
1088
     * @param   String      $form - create/update - to determine what fields should be compacted
1089
     * @return  array
1090
     */
1091
    public function compactFakeFields($request, $form = 'create')
1092
    {
1093
        $fake_field_columns_to_encode = [];
1094
1095
        // get the right fields according to the form type (create/update)
1096 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...
1097
            case 'update':
1098
                $fields = $this->update_fields;
1099
                break;
1100
1101
            default:
1102
                $fields = $this->create_fields;
1103
                break;
1104
        }
1105
1106
        // go through each defined field
1107
        foreach ($fields as $k => $field) {
1108
            // if it's a fake field
1109
            if (isset($fields[$k]['fake']) && $fields[$k]['fake'] == true) {
1110
                // add it to the request in its appropriate variable - the one defined, if defined
1111
                if (isset($fields[$k]['store_in'])) {
1112
                    $request[$fields[$k]['store_in']][$fields[$k]['name']] = $request[$fields[$k]['name']];
1113
1114
                    $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...
1115 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...
1116
                        array_push($fake_field_columns_to_encode, $fields[$k]['store_in']);
1117
                    }
1118
                } else //otherwise in the one defined in the $crud variable
1119
                {
1120
                    $request['extras'][$fields[$k]['name']] = $request[$fields[$k]['name']];
1121
1122
                    $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...
1123
                    if (!in_array('extras', $fake_field_columns_to_encode, true)) {
1124
                        array_push($fake_field_columns_to_encode, 'extras');
1125
                    }
1126
                }
1127
            }
1128
        }
1129
1130
        // json_encode all fake_value columns in the database, so they can be properly stored and interpreted
1131
        if (count($fake_field_columns_to_encode)) {
1132
            foreach ($fake_field_columns_to_encode as $key => $value) {
1133
                $request[$value] = json_encode($request[$value]);
1134
            }
1135
        }
1136
1137
        // if there are no fake fields defined, this will just return the original Request in full
1138
        // since no modifications or additions have been made to $request
1139
        return $request;
1140
    }
1141
1142
1143
    /**
1144
     * Returns an array of database columns names, that are used to store fake values.
1145
     * Returns ['extras'] if no columns have been found.
1146
     *
1147
     */
1148
    public function getFakeColumnsAsArray($form = 'create')
1149
    {
1150
        $fake_field_columns_to_encode = [];
1151
1152
        // get the right fields according to the form type (create/update)
1153 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...
1154
            case 'update':
1155
                $fields = $this->update_fields;
1156
                break;
1157
1158
            default:
1159
                $fields = $this->create_fields;
1160
                break;
1161
        }
1162
1163
1164
        foreach ($fields as $k => $field) {
1165
            // if it's a fake field
1166
            if (isset($fields[$k]['fake']) && $fields[$k]['fake'] == true) {
1167
                // add it to the request in its appropriate variable - the one defined, if defined
1168
                if (isset($fields[$k]['store_in'])) {
1169 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...
1170
                        array_push($fake_field_columns_to_encode, $fields[$k]['store_in']);
1171
                    }
1172
                } else //otherwise in the one defined in the $crud variable
1173
                {
1174
                    if (!in_array('extras', $fake_field_columns_to_encode, true)) {
1175
                        array_push($fake_field_columns_to_encode, 'extras');
1176
                    }
1177
                }
1178
            }
1179
        }
1180
1181
        if (!count($fake_field_columns_to_encode)) {
1182
            return ['extras'];
1183
        }
1184
1185
        return $fake_field_columns_to_encode;
1186
    }
1187
1188
1189
1190
1191
1192
1193
1194
1195
    // ----------------------------------
1196
    // Miscellaneous functions or methods
1197
    // ----------------------------------
1198
1199
1200
    /**
1201
     * Return the first element in an array that has the given 'type' attribute.
1202
     * @param  string $type
1203
     * @param  array $array
1204
     * @return array
1205
     */
1206
    public function getFirstOfItsTypeInArray($type, $array)
1207
    {
1208
        return array_first($array, function($key, $item) use ($type) {
1209
            return $item['type'] == $type;
1210
        });
1211
    }
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
    // ------------
1224
    // TONE FUNCTIONS - UNDOCUMENTED, UNTESTED, SOME MAY BE USED IN THIS FILE
1225
    // ------------
1226
    //
1227
    // TODO:
1228
    // - figure out if they are really needed
1229
    // - comments inside the function to explain how they work
1230
    // - write docblock for them
1231
    // - place in the correct section above (CREATE, READ, UPDATE, DELETE, ACCESS, MANIPULATION)
1232
1233
1234
1235
    public function addButton($button)
1236
    {
1237
        array_unshift($this->buttons, $button);
1238
    }
1239
1240
    public function buttons()
1241
    {
1242
        return $this->buttons;
1243
    }
1244
1245
    public function addCustomButton($button)
1246
    {
1247
        array_unshift($this->custom_buttons, $button);
1248
    }
1249
1250
    public function customButtons()
1251
    {
1252
        return $this->custom_buttons;
1253
    }
1254
1255
    public function showButtons()
1256
    {
1257
        return !empty($this->buttons) && !(count($this->buttons) == 1 && array_key_exists('add', $this->buttons));
1258
    }
1259
1260
    public function initButtons()
1261
    {
1262
        $this->buttons = [
1263
            'add' => ['route' => "{$this->route}/create", 'label' => trans('crud::crud.buttons.add'), 'class' => '', 'hide' => [], 'icon' => 'fa-plus-circle', 'extra' => []],
1264
            'view' => ['route' => "{$this->route}/%d", 'label' => trans('crud::crud.buttons.view'), 'class' => '', 'hide' => [], 'icon' => 'fa-eye', 'extra' => []],
1265
            'edit' => ['route' => "{$this->route}/%d/edit", 'label' => trans('crud::crud.buttons.edit'), 'class' => '', 'hide' => [], 'icon' => 'fa-edit', 'extra' => []],
1266
            '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']],
1267
        ];
1268
    }
1269
1270
    public function removeButtons($buttons)
1271
    {
1272
        foreach ($buttons as $button)
1273
        {
1274
            unset($this->buttons[$button]);
1275
        }
1276
1277
        return $this->buttons;
1278
    }
1279
1280
1281
1282
1283
1284
1285
1286
1287
    public function getColumns()
1288
    {
1289
        return $this->sort('columns');
1290
    }
1291
1292
    public function orderColumns($order)
1293
    {
1294
        $this->setSort('columns', (array)$order);
1295
    }
1296
1297
1298
1299
1300
1301
1302
    public function setFields($fields)
1303
    {
1304
        $this->addMultiple('fields', $fields);
1305
    }
1306
1307
    // [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...
1308
    // 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...
1309
    // {
1310
    //     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...
1311
    // }
1312
1313
    public function updateFields($fields, $attributes)
1314
    {
1315
        $this->sync('fields', $fields, $attributes);
1316
    }
1317
1318
    // 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...
1319
    // {
1320
    //     $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...
1321
    //     $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...
1322
    // }
1323
1324
    public function setCreateFields($fields)
1325
    {
1326
        $this->addMultiple('create_fields', $fields);
1327
    }
1328
1329
    public function addCreateField($field)
1330
    {
1331
       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...
1332
    }
1333
1334
     public function setUpdateFields($fields)
1335
    {
1336
        $this->addMultiple('update_fields', $fields);
1337
    }
1338
1339
    public function addUpdateField($field)
1340
    {
1341
        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...
1342
    }
1343
1344
    public function fields()
1345
    {
1346
        if (!$this->entry && !empty($this->create_fields))
1347
        {
1348
            $this->syncRelations('create_fields');
1349
1350
            return $this->create_fields;
1351
        }
1352
1353
        if ($this->entry && !empty($this->update_fields))
1354
        {
1355
            $this->syncRelations('update_fields');
1356
            $this->addFieldsValue();
1357
1358
            return $this->update_fields;
1359
        }
1360
1361
        $this->syncRelations('fields');
1362
        $this->addFieldsValue();
1363
1364
        return $this->sort('fields');
1365
    }
1366
1367
    public function orderFields($order)
1368
    {
1369
        $this->setSort('fields', (array)$order);
1370
    }
1371
1372
1373
    // 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...
1374
    // {
1375
    //     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...
1376
    //         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...
1377
1378
    //     return false;
1379
    // }
1380
1381
1382
1383
1384
1385
    // iti pune valorile pe field-uri la EDIT
1386
    public function addFieldsValue()
1387
    {
1388
        if ($this->entry)
1389
        {
1390
            $fields = !empty($this->update_fields) ? 'update_fields' : 'fields';
1391
1392
            foreach ($this->{$fields} as $key => $field)
1393
            {
1394
                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();
1395
                    else $this->{$fields}[$key]['value'] = $this->entry->{$field['name']};
1396
            }
1397
        }
1398
    }
1399
1400
    // 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...
1401
    // {
1402
    //     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...
1403
    // }
1404
1405
    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...
1406
    {
1407
        $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...
1408
    }
1409
1410
    public function sync($type, $fields, $attributes)
1411
    {
1412
        if (!empty($this->{$type}))
1413
        {
1414
            $this->{$type} = array_map(function($field) use ($fields, $attributes) {
1415
                if (in_array($field['name'], (array)$fields)) $field = array_merge($field, $attributes);
1416
1417
                return $field;
1418
            }, $this->{$type});
1419
        }
1420
    }
1421
1422
1423
1424
    // 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...
1425
    // {
1426
    //     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...
1427
    // }
1428
1429
    public function setSort($items, $order)
1430
    {
1431
        $this->sort[$items] = $order;
1432
    }
1433
1434
    public function sort($items)
1435
    {
1436
        if (array_key_exists($items, $this->sort))
1437
        {
1438
            $elements = [];
1439
1440
            foreach ($this->sort[$items] as $item)
1441
            {
1442
                if (is_numeric($key = array_search($item, array_column($this->{$items}, 'name')))) $elements[] = $this->{$items}[$key];
1443
            }
1444
1445
            return $this->{$items} = array_merge($elements, array_filter($this->{$items}, function($item) use($items) {return !in_array($item['name'], $this->sort[$items]);}));
1446
        }
1447
1448
        return $this->{$items};
1449
    }
1450
1451
1452
1453
1454
1455
    // cred ca ia valorile din tabela de legatura ca sa ti le afiseze in select
1456
    public function getRelationValues($model, $field, $where = [], $order = [])
1457
    {
1458
        $order = (array)$order;
1459
        $values = $model->select('*');
1460
1461
        if (!empty($where)) call_user_func_array([$values, $where[0]], array_slice($where, 1));
1462
1463
        if (!empty($order)) call_user_func_array([$values, 'orderBy'], $order);
1464
1465
        return $values->get()->lists($field, $model->getKeyName())->toArray();
1466
    }
1467
1468
    // face un fel de merge intre ce ii dai si ce e in CRUD
1469
    public function syncRelations($entity)
1470
    {
1471
        foreach ($this->relations as $field => $relation) {
1472
            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...
1473
                else $this->sync($entity, $field, ['type' => 'select', 'values' => $this->relations[$field]['values']]);
1474
        }
1475
    }
1476
1477
1478
1479
}