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 ( c61b79...4016a1 )
by Cristian
09:20
created

Crud::buttons()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

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

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

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

Loading history...
63
     */
64
    public function create($data)
65
    {
66
        $values_to_store = $this->compactFakeFields(\Request::all());
0 ignored issues
show
Documentation introduced by
\Request::all() is of type array, but the function expects a object<Backpack\CRUD\Request>.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
67
        $item = $this->model->create($values_to_store);
1 ignored issue
show
Bug introduced by
The method create cannot be called on $this->model (of type string).

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

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

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

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
84
    }
85
86
87
88
89 View Code Duplication
    public function syncPivot($model, $data)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
90
    {
91
        foreach ($this->relations as $key => $relation)
92
        {
93
            if ($relation['pivot']){
94
                $model->{$relation['name']}()->sync($data[$key]);
95
96
                foreach($relation['pivotFields'] as $pivotField){
97
                   foreach($data[$pivotField] as $pivot_id =>  $field){
98
                     $model->{$relation['name']}()->updateExistingPivot($pivot_id, [$pivotField => $field]);
99
                   }
100
                }
101
            }
102
        }
103
    }
104
105
106
107
    /**
108
     * Adds a required => true attribute to each field, so that the required asterisc will show up in the create/update forms.
109
     * TODO: make this work, by editing the $this->fields variable.
110
     *
111
     * @param [string or array of strings]
112
     */
113
    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...
114
    {
115
        // TODO
116
    }
117
118
    /**
119
     * Adds a required => true attribute to this field, so that the required asteris will show up in the create/update forms.
120
     *
121
     * @param [string]
122
     */
123
    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...
124
    {
125
        // TODO
126
    }
127
128
    /**
129
     * Get all fields that have the required attribute.
130
     * TODO: make this work after making setRequiredFields() work.
131
     *
132
     * @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...
133
     */
134
    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...
135
    {
136
        // TODO
137
    }
138
139
140
   /*
141
    |--------------------------------------------------------------------------
142
    |                                   READ
143
    |--------------------------------------------------------------------------
144
    */
145
146
    /**
147
     * Find and retrieve an entry in the database or fail.
148
     *
149
     * @param  [int] The id of the row in the db to fetch.
150
     * @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...
151
     */
152
    public function getEntry($id)
153
    {
154
        $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...
155
        return $entry->withFakes();
156
    }
157
158
159
    /**
160
     * Get all entries from the database.
161
     *
162
     * @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...
163
     */
164
    public function getEntries()
165
    {
166
        $entries = $this->query->get();
167
168
        // add the fake columns for each entry
169
        foreach ($entries as $key => $entry) {
170
            $entry->addFakes($this->getFakeColumnsAsArray());
171
        }
172
173
        return $entries;
174
    }
175
176
177
    /**
178
     * Get the fields for the create or update forms.
179
     *
180
     * @param  [form] create / update / both - defaults to 'both'
181
     * @param  [integer] the ID of the entity to be edited in the Update form
182
     * @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...
183
     */
184
    public function getFields($form, $id = false)
185
    {
186
        switch ($form) {
187
            case 'create':
188
                return $this->getCreateFields();
189
                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...
190
191
            case 'update':
192
                return $this->getUpdateFields($id);
193
                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...
194
195
            default:
196
                return $this->getCreateFields();
197
                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...
198
        }
199
    }
200
201
202
    /**
203
     * Enable the DETAILS ROW functionality:
204
     *
205
     * In the table view, show a plus sign next to each entry.
206
     * 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.
207
     */
208
    public function enableDetailsRow()
209
    {
210
        $this->details_row = true;
211
    }
212
213
    /**
214
     * Disable the DETAILS ROW functionality:
215
     */
216
    public function disableDetailsRow()
217
    {
218
        $this->details_row = false;
219
    }
220
221
222
223
   /*
224
    |--------------------------------------------------------------------------
225
    |                                   UPDATE
226
    |--------------------------------------------------------------------------
227
    */
228
229
    /**
230
     * Update a row in the database.
231
     *
232
     * @param  [Int] The entity's id
233
     * @param  [Request] All inputs to be updated.
234
     * @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...
235
     */
236 View Code Duplication
    public function update($id, $data)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
237
    {
238
        $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...
239
        $updated = $item->update($this->compactFakeFields($data));
240
241
        if ($updated) $this->syncPivot($item, $data);
242
243
        return $item;
244
    }
245
246
247
    /**
248
     * Get all fields needed for the EDIT ENTRY form.
249
     *
250
     * @param  [integer] The id of the entry that is being edited.
251
     * @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...
252
     */
253
    public function getUpdateFields($id)
254
    {
255
        $fields = $this->prepareFields(empty($this->update_fields)?$this->fields:$this->update_fields);
0 ignored issues
show
Documentation introduced by
empty($this->update_fiel... : $this->update_fields is of type array, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
256
        $entry = $this->getEntry($id);
257
258 View Code Duplication
        foreach ($fields as $k => $field) {
0 ignored issues
show
Bug introduced by
The expression $fields of type boolean is not traversable.
Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
259
            // set the value
260
            if (!isset($fields[$k]['value']))
261
            {
262
                $fields[$k]['value'] = $entry->$field['name'];
263
            }
264
        }
265
266
        // always have a hidden input for the entry id
267
        $fields[] = array(
268
                        'name' => 'id',
269
                        'value' => $entry->id,
270
                        'type' => 'hidden'
271
                    );
272
273
        return $fields;
274
    }
275
276
277
278
279
   /*
280
    |--------------------------------------------------------------------------
281
    |                                   DELETE
282
    |--------------------------------------------------------------------------
283
    */
284
285
    /**
286
     * Delete a row from the database.
287
     *
288
     * @param  [int] The id of the item to be deleted.
289
     * @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...
290
     *
291
     * TODO: should this delete items with relations to it too?
292
     */
293
    public function delete($id)
294
    {
295
        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...
296
    }
297
298
299
300
301
    /*
302
    |--------------------------------------------------------------------------
303
    |                                   REORDER
304
    |--------------------------------------------------------------------------
305
    */
306
307
308
    /**
309
     * Change the order and parents of the given elements, according to the NestedSortable AJAX call.
310
     *
311
     * @param  [Request] The entire request from the NestedSortable AJAX Call.
312
     * @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...
313
     */
314
    public function updateTreeOrder($request)
315
    {
316
        $count = 0;
317
318
        foreach ($request as $key => $entry) {
319
            if ($entry['item_id'] != "" && $entry['item_id'] != null) {
320
                $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...
321
                $item->parent_id = $entry['parent_id'];
322
                $item->depth = $entry['depth'];
323
                $item->lft = $entry['left'];
324
                $item->rgt = $entry['right'];
325
                $item->save();
326
327
                $count++;
328
            }
329
        }
330
331
        return $count;
332
    }
333
334
335
    /**
336
     * Enable the Reorder functionality in the CRUD Panel for users that have the been given access to 'reorder' using:
337
     * $this->crud->allowAccess('reorder');
338
     *
339
     * @param  [string] Column name that will be shown on the labels.
340
     * @param  [integer] Maximum hierarchy level to which the elements can be nested (1 = no nesting, just reordering).
341
     */
342
    public function enableReorder($label = 'name', $max_level = 1)
343
    {
344
        $this->reorder = true;
345
        $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...
346
        $this->reorder_max_level = $max_level;
347
    }
348
349
    /**
350
     * Disable the Reorder functionality in the CRUD Panel for all users.
351
     *
352
     */
353
    public function disableReorder()
354
    {
355
        $this->reorder = false;
356
    }
357
358
    /**
359
     * Check if the Reorder functionality is enabled or not.
360
     *
361
     * @return boolean
362
     */
363
    public function isReorderEnabled()
364
    {
365
        return $this->reorder;
366
    }
367
368
369
370
   /*
371
    |--------------------------------------------------------------------------
372
    |                                   CRUD ACCESS
373
    |--------------------------------------------------------------------------
374
    */
375
376
    public function allowAccess($access)
377
    {
378
        // $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...
379
        return $this->access = array_merge(array_diff((array)$access, $this->access), $this->access);
380
    }
381
382
    public function denyAccess($access)
383
    {
384
        // $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...
385
        return $this->access = array_diff($this->access, (array)$access);
386
    }
387
388
    /**
389
     * Check if a permission is enabled for a Crud Panel. Return false if not.
390
     *
391
     * @param  [string] Permission.
392
     * @return boolean
393
     */
394
    public function hasAccess($permission)
395
    {
396
        if (!in_array($permission, $this->access))
397
        {
398
            return false;
399
        }
400
        return true;
401
    }
402
403
    /**
404
     * Check if a permission is enabled for a Crud Panel. Fail if not.
405
     *
406
     * @param  [string] Permission.
407
     * @return boolean
408
     */
409
    public function hasAccessOrFail($permission)
410
    {
411
        if (!in_array($permission, $this->access))
412
        {
413
            abort(403, trans('backpack::crud.unauthorized_access'));
414
        }
415
    }
416
417
418
419
    /*
420
    |--------------------------------------------------------------------------
421
    |                               CRUD MANIPULATION
422
    |--------------------------------------------------------------------------
423
    */
424
425
426
427
    // ------------------------------------------------------
428
    // BASICS - model, route, entity_name, entity_name_plural
429
    // ------------------------------------------------------
430
431
    /**
432
     * This function binds the CRUD to its corresponding Model (which extends Eloquent).
433
     * All Create-Read-Update-Delete operations are done using that Eloquent Collection.
434
     *
435
     * @param [string] Full model namespace. Ex: App\Models\Article
436
     */
437 View Code Duplication
    public function setModel($model_namespace)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
438
    {
439
        if (!class_exists($model_namespace)) throw new \Exception('This model does not exist.', 404);
440
441
        $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...
442
        $this->query = $this->model->select('*');
443
444
        // $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...
445
    }
446
447
    /**
448
     * Get the corresponding Eloquent Model for the CrudController, as defined with the setModel() function;
449
     *
450
     * @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...
451
     */
452
    public function getModel()
453
    {
454
        return $this->model;
455
    }
456
457
    /**
458
     * Set the route for this CRUD.
459
     * Ex: admin/article
460
     *
461
     * @param [string] Route name.
462
     * @param [array] Parameters.
463
     */
464
    public function setRoute($route)
465
    {
466
        $this->route = $route;
467
        $this->initButtons();
468
    }
469
470
    /**
471
     * Set the route for this CRUD using the route name.
472
     * Ex: admin.article
473
     *
474
     * @param [string] Route name.
475
     * @param [array] Parameters.
476
     */
477 View Code Duplication
    public function setRouteName($route, $parameters = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
478
    {
479
        $complete_route = $route.'.index';
480
481
        if (!\Route::has($complete_route)) throw new \Exception('There are no routes for this route name.', 404);
482
483
        $this->route = route($complete_route, $parameters);
484
        $this->initButtons();
485
    }
486
487
    /**
488
     * Get the current CrudController route.
489
     *
490
     * Can be defined in the CrudController with:
491
     * - $this->crud->setRoute('admin/article')
492
     * - $this->crud->setRouteName('admin.article')
493
     * - $this->crud->route = "admin/article"
494
     *
495
     * @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...
496
     */
497
    public function getRoute()
498
    {
499
        return $this->route;
500
    }
501
502
    /**
503
     * Set the entity name in singular and plural.
504
     * Used all over the CRUD interface (header, add button, reorder button, breadcrumbs).
505
     *
506
     * @param [string] Entity name, in singular. Ex: article
507
     * @param [string] Entity name, in plural. Ex: articles
508
     */
509
    public function setEntityNameStrings($singular, $plural) {
510
        $this->entity_name = $singular;
511
        $this->entity_name_plural = $plural;
512
    }
513
514
515
516
517
    // ------------
518
    // COLUMNS
519
    // ------------
520
521
    /**
522
     * Add a bunch of column names and their details to the CRUD object.
523
     *
524
     * @param [array or multi-dimensional array]
525
     */
526
    public function setColumns($columns)
527
    {
528
        // clear any columns already set
529
        $this->columns = [];
530
531
        // if array, add a column for each of the items
532
        if (is_array($columns) && count($columns)) {
533
            foreach ($columns as $key => $column) {
534
                // if label and other details have been defined in the array
535
                if (is_array($columns[0])) {
536
                    $this->addColumn($column);
537
                }
538
                else
539
                {
540
                    $this->addColumn([
541
                                    'name' => $column,
542
                                    'label' => ucfirst($column),
543
                                    'type' => 'text'
544
                                ]);
545
                }
546
            }
547
        }
548
549
        if (is_string($columns)) {
550
            $this->addColumn([
551
                                'name' => $columns,
552
                                'label' => ucfirst($columns),
553
                                'type' => 'text'
554
                                ]);
555
        }
556
557
        // This was the old setColumns() function, and it did not work:
558
        // $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...
559
    }
560
561
    /**
562
     * Add a column at the end of to the CRUD object's "columns" array.
563
     *
564
     * @param [string or array]
565
     */
566
    public function addColumn($column)
567
    {
568
        // make sure the column has a type
569
        $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...
570
571
        // make sure the column has a label
572
        $column_with_details = $this->addDefaultLabel($column);
573
574
        return array_filter($this->columns[] = $column_with_details);
575
    }
576
577
    /**
578
     * Add multiple columns at the end of the CRUD object's "columns" array.
579
     *
580
     * @param [array of columns]
581
     */
582
    public function addColumns($columns)
583
    {
584
        if (count($columns)) {
585
            foreach ($columns as $key => $column) {
586
                $this->addColumn($column);
587
            }
588
        }
589
    }
590
591
    /**
592
     * Add the default column type to the given Column, inferring the type from the database column type.
593
     *
594
     * @param [column array]
595
     */
596
    public function addDefaultTypeToColumn($column)
597
    {
598
        if (array_key_exists('name', (array)$column))
599
        {
600
            $default_type = $this->getFieldTypeFromDbColumnType($column['name']);
601
            return array_merge(['type' => $default_type], $column);
602
        }
603
604
        return false;
605
    }
606
607
    /**
608
     * If a field or column array is missing the "label" attribute, an ugly error would be show.
609
     * So we add the field Name as a label - it's better than nothing.
610
     *
611
     * @param [field or column]
612
     */
613
    public function addDefaultLabel($array) {
614
        if (!array_key_exists('label', (array)$array) && array_key_exists('name', (array)$array)) {
615
            $array = array_merge(['label' => ucfirst($this->makeLabel($array['name']))], $array);
616
            return $array;
617
        }
618
619
        return $array;
620
    }
621
622
    /**
623
     * Remove multiple columns from the CRUD object using their names.
624
     *
625
     * @param  [column array]
626
     */
627
    public function removeColumns($columns)
628
    {
629
        $this->columns = $this->remove('columns', $columns);
630
    }
631
632
    /**
633
     * Remove a column from the CRUD object using its name.
634
     *
635
     * @param  [column array]
636
     */
637
    public function removeColumn($column)
638
    {
639
        return $this->removeColumns([$column]);
640
    }
641
642
    /**
643
     * Change attributes for multiple columns.
644
     *
645
     * @param [columns arrays]
646
     * @param [attributes and values array]
647
     */
648
    public function setColumnsDetails($columns, $attributes)
649
    {
650
        $this->sync('columns', $columns, $attributes);
651
    }
652
653
    /**
654
     * Change attributes for a certain column.
655
     *
656
     * @param [string] Column name.
657
     * @param [attributes and values array]
658
     */
659
    public function setColumnDetails($column, $attributes)
660
    {
661
        $this->setColumnsDetails([$column], $attributes);
662
    }
663
664
665
    /**
666
     * Order the columns in a certain way.
667
     *
668
     * @param [string] Column name.
669
     * @param [attributes and values array]
670
     */
671
    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...
672
    {
673
        // TODO
674
    }
675
676
    // ALIAS of setColumnOrder($columns)
677
    public function setColumnsOrder($columns) { $this->setColumnOrder($columns); }
678
679
680
    // ------------
681
    // FIELDS
682
    // ------------
683
684
685
    /**
686
     * Order the fields in a certain way.
687
     *
688
     * @param [string] Column name.
689
     * @param [attributes and values array]
690
     */
691
    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...
692
    {
693
        // TODO
694
    }
695
696
    // ALIAS of setFieldOrder($fields)
697
    public function setFieldsOrder($fields) { $this->setFieldOrder($fields); }
698
699
700
    // ----------------
701
    // ADVANCED QUERIES
702
    // ----------------
703
704
705
    /**
706
     * Add another clause to the query (for ex, a WHERE clause).
707
     *
708
     * Examples:
709
     * // $this->crud->addClause('active');
710
     * $this->crud->addClause('type', 'car');
711
     * $this->crud->addClause('where', 'name', '==', 'car');
712
     * $this->crud->addClause('whereName', 'car');
713
     * $this->crud->addClause('whereHas', 'posts', function($query) {
714
     *     $query->activePosts();
715
     *     });
716
     *
717
     * @param [type]
718
     */
719
    public function addClause($function)
720
    {
721
        return call_user_func_array([$this->query, $function], array_slice(func_get_args(), 1, 3));
722
    }
723
724
    /**
725
     * Order the results of the query in a certain way.
726
     *
727
     * @param  [type]
728
     * @param  string
729
     * @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...
730
     */
731
    public function orderBy($field, $order = 'asc')
732
    {
733
        return $this->query->orderBy($field, $order);
734
    }
735
736
    /**
737
     * Group the results of the query in a certain way.
738
     *
739
     * @param  [type]
740
     * @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...
741
     */
742
    public function groupBy($field)
743
    {
744
        return $this->query->groupBy($field);
745
    }
746
747
    /**
748
     * Limit the number of results in the query.
749
     *
750
     * @param  [number]
751
     * @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...
752
     */
753
    public function limit($number)
754
    {
755
        return $this->query->limit($number);
756
    }
757
758
759
760
    // ------------
761
    // BUTTONS
762
    // ------------
763
764
    // 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...
765
    // 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...
766
    // 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...
767
    // 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...
768
769
770
771
    // ------------------------------------------------------
772
    // AUTO-SET-FIELDS-AND-COLUMNS FUNCTIONALITY
773
    // ------------------------------------------------------
774
775
776
    /**
777
     * For a simple CRUD Panel, there should be no need to add/define the fields.
778
     * The public columns in the database will be converted to be fields.
779
     *
780
     */
781
    public function setFromDb()
782
    {
783
        $this->getDbColumnTypes();
784
785
        array_map(function($field) {
786
            // $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...
787
788
            $this->fields[] =  [
789
                                'name' => $field,
790
                                'label' => ucfirst($field),
791
                                'value' => '', 'default' => $this->field_types[$field]['default'],
792
                                'type' => $this->getFieldTypeFromDbColumnType($field),
793
                                'values' => [],
794
                                'attributes' => []
795
                                ];
796
797 View Code Duplication
            if (!in_array($field, $this->model->getHidden()))
1 ignored issue
show
Bug introduced by
The method getHidden cannot be called on $this->model (of type string).

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

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

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

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

Loading history...
798
            {
799
                 $this->columns[] = [
800
                                    'name' => $field,
801
                                    'label' => ucfirst($field),
802
                                    'type' => $this->getFieldTypeFromDbColumnType($field)
803
                                    ];
804
            }
805
806
        }, $this->getDbColumnsNames());
807
    }
808
809
810
    /**
811
     * Get all columns from the database for that table.
812
     *
813
     * @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...
814
     */
815 View Code Duplication
    public function getDbColumnTypes()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
816
    {
817
        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...
818
        {
819
            $this->field_types[$column->Field] = ['type' => trim(preg_replace('/\(\d+\)(.*)/i', '', $column->Type)), 'default' => $column->Default];
820
        }
821
822
        return $this->field_types;
823
    }
824
825
826
    /**
827
     * Intuit a field type, judging from the database column type.
828
     *
829
     * @param  [string] Field name.
830
     * @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...
831
     */
832 View Code Duplication
    public function getFieldTypeFromDbColumnType($field)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
833
    {
834
        if (!array_key_exists($field, $this->field_types)) return 'text';
835
836
        if ($field == 'password') return 'password';
837
838
        if ($field == 'email') return 'email';
839
840
        switch ($this->field_types[$field]['type'])
841
        {
842
            case 'int':
843
            case 'smallint':
844
            case 'mediumint':
845
            case 'longint':
846
                return 'number';
847
            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...
848
849
            case 'string':
850
            case 'varchar':
851
            case 'set':
852
                return 'text';
853
            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...
854
855
            // case 'enum':
856
            //     return 'enum';
857
            // break;
858
859
            case 'tinyint':
860
                return 'active';
861
            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...
862
863
            case 'text':
864
            case 'mediumtext':
865
            case 'longtext':
866
                return 'textarea';
867
            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...
868
869
            case 'date':
870
                return 'date';
871
            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...
872
873
            case 'datetime':
874
            case 'timestamp':
875
                return 'datetime';
876
            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...
877
            case 'time':
878
                return 'time';
879
            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...
880
881
            default:
882
                return 'text';
883
            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...
884
        }
885
    }
886
887
888
    /**
889
     * Turn a database column name or PHP variable into a pretty label to be shown to the user.
890
     *
891
     * @param  [string]
892
     * @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...
893
     */
894
    public function makeLabel($value)
895
    {
896
        return trim(preg_replace('/(id|at|\[\])$/i', '', ucfirst(str_replace('_', ' ', $value))));
897
    }
898
899
900
    /**
901
     * Get the database column names, in order to figure out what fields/columns to show in the auto-fields-and-columns functionality.
902
     *
903
     * @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...
904
     */
905 View Code Duplication
    public function getDbColumnsNames()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
906
    {
907
        // Automatically-set columns should be both in the database, and in the $fillable variable on the Eloquent Model
908
        $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...
909
        $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...
910
911
        if (!empty($fillable)) $columns = array_intersect($columns, $fillable);
912
913
        // but not updated_at, deleted_at
914
        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...
915
    }
916
917
918
919
920
921
922
923
    // -----------------
924
    // Commodity methods
925
    // -----------------
926
927
928
    /**
929
     * Prepare the fields to be shown, stored, updated or created.
930
     *
931
     * Makes sure $this->crud->fields is in the proper format (array of arrays);
932
     * Makes sure $this->crud->fields also contains the id of the current item;
933
     * Makes sure $this->crud->fields also contains the values for each field;
934
     *
935
     */
936
    public function prepareFields($fields = false)
937
    {
938
        // if no field type is defined, assume the "text" field type
939 View Code Duplication
        foreach ($fields as $k => $field) {
0 ignored issues
show
Bug introduced by
The expression $fields of type boolean is not traversable.
Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
940
                if (!isset($fields[$k]['type'])) {
941
                    $fields[$k]['type'] = 'text';
942
                }
943
            }
944
945
        return $fields;
946
    }
947
948
949
950
    /**
951
     * Refactor the request array to something that can be passed to the model's create or update function.
952
     * The resulting array will only include the fields that are stored in the database and their values,
953
     * plus the '_token' and 'redirect_after_save' variables.
954
     *
955
     * @param   Request     $request - everything that was sent from the form, usually \Request::all()
956
     * @return  array
957
     */
958
    public function compactFakeFields($request) {
959
960
        // $this->prepareFields();
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% of this comment could be valid code. Did you maybe forget this after debugging?

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

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

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

Loading history...
961
962
        $fake_field_columns_to_encode = [];
963
964
        // go through each defined field
965
        foreach ($this->fields as $k => $field) {
966
            // if it's a fake field
967
            if (isset($this->fields[$k]['fake']) && $this->fields[$k]['fake'] == true) {
968
                // add it to the request in its appropriate variable - the one defined, if defined
969
                if (isset($this->fields[$k]['store_in'])) {
970
                    $request[$this->fields[$k]['store_in']][$this->fields[$k]['name']] = $request[$this->fields[$k]['name']];
971
972
                    $remove_fake_field = array_pull($request, $this->fields[$k]['name']);
0 ignored issues
show
Unused Code introduced by
$remove_fake_field is not used, you could remove the assignment.

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

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

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

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

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

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

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

Loading history...
974
                        array_push($fake_field_columns_to_encode, $this->fields[$k]['store_in']);
975
                    }
976
                } else //otherwise in the one defined in the $crud variable
977
                {
978
                    $request['extras'][$this->fields[$k]['name']] = $request[$this->fields[$k]['name']];
979
980
                    $remove_fake_field = array_pull($request, $this->fields[$k]['name']);
0 ignored issues
show
Unused Code introduced by
$remove_fake_field is not used, you could remove the assignment.

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

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

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

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

Loading history...
981
                    if (!in_array('extras', $fake_field_columns_to_encode, true)) {
982
                        array_push($fake_field_columns_to_encode, 'extras');
983
                    }
984
                }
985
            }
986
        }
987
988
        // json_encode all fake_value columns in the database, so they can be properly stored and interpreted
989
        if (count($fake_field_columns_to_encode)) {
990
            foreach ($fake_field_columns_to_encode as $key => $value) {
991
                $request[$value] = json_encode($request[$value]);
992
            }
993
        }
994
995
        // if there are no fake fields defined, this will just return the original Request in full
996
        // since no modifications or additions have been made to $request
997
        return $request;
998
    }
999
1000
1001
    /**
1002
     * Returns an array of database columns names, that are used to store fake values.
1003
     * Returns ['extras'] if no columns have been found.
1004
     *
1005
     */
1006
    public function getFakeColumnsAsArray() {
1007
1008
        // $this->prepareFields();
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% of this comment could be valid code. Did you maybe forget this after debugging?

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

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

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

Loading history...
1009
1010
        $fake_field_columns_to_encode = [];
1011
1012
        foreach ($this->fields as $k => $field) {
1013
            // if it's a fake field
1014
            if (isset($this->fields[$k]['fake']) && $this->fields[$k]['fake'] == true) {
1015
                // add it to the request in its appropriate variable - the one defined, if defined
1016
                if (isset($this->fields[$k]['store_in'])) {
1017 View Code Duplication
                    if (!in_array($this->fields[$k]['store_in'], $fake_field_columns_to_encode, true)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
1018
                        array_push($fake_field_columns_to_encode, $this->fields[$k]['store_in']);
1019
                    }
1020
                } else //otherwise in the one defined in the $crud variable
1021
                {
1022
                    if (!in_array('extras', $fake_field_columns_to_encode, true)) {
1023
                        array_push($fake_field_columns_to_encode, 'extras');
1024
                    }
1025
                }
1026
            }
1027
        }
1028
1029
        if (!count($fake_field_columns_to_encode)) {
1030
            return ['extras'];
1031
        }
1032
1033
        return $fake_field_columns_to_encode;
1034
    }
1035
1036
1037
1038
1039
1040
1041
1042
1043
    // ----------------------------------
1044
    // Miscellaneous functions or methods
1045
    // ----------------------------------
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
    // ------------
1060
    // TONE FUNCTIONS - UNDOCUMENTED, UNTESTED, SOME MAY BE USED IN THIS FILE
1061
    // ------------
1062
    //
1063
    // TODO:
1064
    // - figure out if they are really needed
1065
    // - comments inside the function to explain how they work
1066
    // - write docblock for them
1067
    // - place in the correct section above (CREATE, READ, UPDATE, DELETE, ACCESS, MANIPULATION)
1068
1069
1070
1071
    public function addButton($button)
1072
    {
1073
        array_unshift($this->buttons, $button);
1074
    }
1075
1076
    public function buttons()
1077
    {
1078
        return $this->buttons;
1079
    }
1080
1081
    public function addCustomButton($button)
1082
    {
1083
        array_unshift($this->custom_buttons, $button);
1084
    }
1085
1086
    public function customButtons()
1087
    {
1088
        return $this->custom_buttons;
1089
    }
1090
1091
    public function showButtons()
1092
    {
1093
        return !empty($this->buttons) && !(count($this->buttons) == 1 && array_key_exists('add', $this->buttons));
1094
    }
1095
1096 View Code Duplication
    public function initButtons()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
1097
    {
1098
        $this->buttons = [
1099
            'add' => ['route' => "{$this->route}/create", 'label' => trans('crud::crud.buttons.add'), 'class' => '', 'hide' => [], 'icon' => 'fa-plus-circle', 'extra' => []],
1100
            'view' => ['route' => "{$this->route}/%d", 'label' => trans('crud::crud.buttons.view'), 'class' => '', 'hide' => [], 'icon' => 'fa-eye', 'extra' => []],
1101
            'edit' => ['route' => "{$this->route}/%d/edit", 'label' => trans('crud::crud.buttons.edit'), 'class' => '', 'hide' => [], 'icon' => 'fa-edit', 'extra' => []],
1102
            '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']],
1103
        ];
1104
    }
1105
1106
    public function removeButtons($buttons)
1107
    {
1108
        foreach ($buttons as $button)
1109
        {
1110
            unset($this->buttons[$button]);
1111
        }
1112
1113
        return $this->buttons;
1114
    }
1115
1116
1117
1118
1119
1120
1121
1122
1123
    public function getColumns()
1124
    {
1125
        return $this->sort('columns');
1126
    }
1127
1128
    public function orderColumns($order)
1129
    {
1130
        $this->setSort('columns', (array)$order);
1131
    }
1132
1133
1134
1135
1136
1137
1138
    public function setFields($fields)
1139
    {
1140
        $this->addMultiple('fields', $fields);
1141
    }
1142
1143
    // [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...
1144
    public function addField($field)
1145
    {
1146
        return $this->add('fields', $field);
1147
    }
1148
1149
    public function updateFields($fields, $attributes)
1150
    {
1151
        $this->sync('fields', $fields, $attributes);
1152
    }
1153
1154
    public function removeFields($fields)
1155
    {
1156
        $this->fields = $this->remove('fields', $fields);
1157
        $this->removeColumns($fields);
1158
    }
1159
1160
    public function setCreateFields($fields)
1161
    {
1162
        $this->addMultiple('create_fields', $fields);
1163
    }
1164
1165
    public function addCreateField($field)
1166
    {
1167
       return $this->add('create_fields', $field);
1168
    }
1169
1170
     public function setUpdateFields($fields)
1171
    {
1172
        $this->addMultiple('update_fields', $fields);
1173
    }
1174
1175
    public function addUpdateField($field)
1176
    {
1177
        return $this->add('update_fields', $field);
1178
    }
1179
1180 View Code Duplication
    public function fields()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
1181
    {
1182
        if (!$this->entry && !empty($this->create_fields))
1183
        {
1184
            $this->syncRelations('create_fields');
1185
1186
            return $this->create_fields;
1187
        }
1188
1189
        if ($this->entry && !empty($this->update_fields))
1190
        {
1191
            $this->syncRelations('update_fields');
1192
            $this->addFieldsValue();
1193
1194
            return $this->update_fields;
1195
        }
1196
1197
        $this->syncRelations('fields');
1198
        $this->addFieldsValue();
1199
1200
        return $this->sort('fields');
1201
    }
1202
1203
    public function orderFields($order)
1204
    {
1205
        $this->setSort('fields', (array)$order);
1206
    }
1207
1208
1209
    public function syncField($field)
1210
    {
1211 View Code Duplication
        if (array_key_exists('name', (array)$field)) return array_merge(['type' => $this->getFieldTypeFromDbColumnType($field['name']), 'value' => '', 'default' => null, 'values' => [], 'attributes' => []], $field);
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
1212
1213
        return false;
1214
    }
1215
1216
1217
1218
1219
1220
    // iti pune valorile pe field-uri la EDIT
1221 View Code Duplication
    public function addFieldsValue()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
1222
    {
1223
        if ($this->entry)
1224
        {
1225
            $fields = !empty($this->update_fields) ? 'update_fields' : 'fields';
1226
1227
            foreach ($this->{$fields} as $key => $field)
1228
            {
1229
                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();
1230
                    else $this->{$fields}[$key]['value'] = $this->entry->{$field['name']};
1231
            }
1232
        }
1233
    }
1234
1235
    public function add($entity, $field)
1236
    {
1237
        return array_filter($this->{$entity}[] = $this->syncField($field));
1238
    }
1239
1240
    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...
1241
    {
1242
        $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...
1243
    }
1244
1245 View Code Duplication
    public function sync($type, $fields, $attributes)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
1246
    {
1247
        if (!empty($this->{$type}))
1248
        {
1249
            $this->{$type} = array_map(function($field) use ($fields, $attributes) {
1250
                if (in_array($field['name'], (array)$fields)) $field = array_merge($field, $attributes);
1251
1252
                return $field;
1253
            }, $this->{$type});
1254
        }
1255
    }
1256
1257
1258
1259
    public function remove($entity, $fields)
1260
    {
1261
        return array_values(array_filter($this->{$entity}, function($field) use ($fields) { return !in_array($field['name'], (array)$fields);}));
1262
    }
1263
1264
    public function setSort($items, $order)
1265
    {
1266
        $this->sort[$items] = $order;
1267
    }
1268
1269 View Code Duplication
    public function sort($items)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
1270
    {
1271
        if (array_key_exists($items, $this->sort))
1272
        {
1273
            $elements = [];
1274
1275
            foreach ($this->sort[$items] as $item)
1276
            {
1277
                if (is_numeric($key = array_search($item, array_column($this->{$items}, 'name')))) $elements[] = $this->{$items}[$key];
1278
            }
1279
1280
            return $this->{$items} = array_merge($elements, array_filter($this->{$items}, function($item) use($items) {return !in_array($item['name'], $this->sort[$items]);}));
1281
        }
1282
1283
        return $this->{$items};
1284
    }
1285
1286
1287
1288
1289
1290
    // cred ca ia valorile din tabela de legatura ca sa ti le afiseze in select
1291 View Code Duplication
    public function getRelationValues($model, $field, $where = [], $order = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
1292
    {
1293
        $order = (array)$order;
1294
        $values = $model->select('*');
1295
1296
        if (!empty($where)) call_user_func_array([$values, $where[0]], array_slice($where, 1));
1297
1298
        if (!empty($order)) call_user_func_array([$values, 'orderBy'], $order);
1299
1300
        return $values->get()->lists($field, $model->getKeyName())->toArray();
1301
    }
1302
1303
    // face un fel de merge intre ce ii dai si ce e in CRUD
1304 View Code Duplication
    public function syncRelations($entity)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
1305
    {
1306
        foreach ($this->relations as $field => $relation) {
1307
            if ($relation['pivot']) $this->add($entity, ['name' => $field, 'type' => 'multiselect', 'value' => [], 'values' => $this->relations[$field]['values']]);
1308
                else $this->sync($entity, $field, ['type' => 'select', 'values' => $this->relations[$field]['values']]);
1309
        }
1310
    }
1311
1312
1313
1314
}