Scrutinizer GitHub App not installed

We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.

Install GitHub App

Completed
Pull Request — master (#134)
by Owen
03:07
created

CrudController::destroy()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 6
rs 9.4285
1
<?php
2
3
namespace Backpack\CRUD\app\Http\Controllers;
4
5
use Backpack\CRUD\app\Http\Requests\CrudRequest as StoreRequest;
6
use Backpack\CRUD\app\Http\Requests\CrudRequest as UpdateRequest;
7
use Backpack\CRUD\CrudPanel;
8
use Illuminate\Foundation\Bus\DispatchesJobs;
9
use Illuminate\Foundation\Validation\ValidatesRequests;
10
// VALIDATION: change the requests to match your own file names if you need form validation
11
use Illuminate\Routing\Controller as BaseController;
12
use Illuminate\Support\Facades\Form as Form;
13
use LiveControl\EloquentDataTable\DataTable;
14
15
class CrudController extends BaseController
16
{
17
    use DispatchesJobs, ValidatesRequests;
18
19
    public $data = [];
20
    public $crud;
21
22
    public function __construct()
23
    {
24
        $this->middleware(function ($request, $next) {
25
            $this->crud = new CrudPanel();
26
            $this->setUp();
27
28
            return $next($request);
29
        });
30
    }
31
32
    /**
33
     * Configures the setup of your crud entity.
34
     */
35
    public function setUp()
36
    {
37
    }
38
39
    /**
40
     * Configures the tear down of your crud entity.
41
     */
42
    public function tearDown()
43
    {
44
        unset($this->crud);
45
    }
46
47
    /**
48
     * Display all rows in the database for this entity.
49
     *
50
     * @return Response
0 ignored issues
show
Documentation introduced by
Should the return type not be \Illuminate\View\View|\I...\Contracts\View\Factory?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
51
     */
52
    public function index()
53
    {
54
        $this->crud->hasAccessOrFail('list');
55
56
        $this->data['crud'] = $this->crud;
57
        $this->data['title'] = ucfirst($this->crud->entity_name_plural);
58
59
        // get all entries if AJAX is not enabled
60
        if (! $this->data['crud']->ajaxTable()) {
61
            $this->data['entries'] = $this->data['crud']->getEntries();
62
        }
63
64
        // load the view from /resources/views/vendor/backpack/crud/ if it exists, otherwise load the one in the package
65
        // $this->crud->getListView() returns 'list' by default, or 'list_ajax' if ajax was enabled
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% 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...
66
        return view('crud::list', $this->data);
67
    }
68
69
    /**
70
     * Show the form for creating inserting a new row.
71
     *
72
     * @return Response
0 ignored issues
show
Documentation introduced by
Should the return type not be \Illuminate\View\View|\I...\Contracts\View\Factory?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
73
     */
74 View Code Duplication
    public function create()
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...
75
    {
76
        $this->crud->hasAccessOrFail('create');
77
78
        // prepare the fields you need to show
79
        $this->data['crud'] = $this->crud;
80
        $this->data['fields'] = $this->crud->getCreateFields();
81
        $this->data['title'] = trans('backpack::crud.add').' '.$this->crud->entity_name;
82
83
        // load the view from /resources/views/vendor/backpack/crud/ if it exists, otherwise load the one in the package
84
        return view('crud::create', $this->data);
85
    }
86
87
    /**
88
     * Store a newly created resource in the database.
89
     *
90
     * @param StoreRequest $request - type injection used for validation using Requests
0 ignored issues
show
Documentation introduced by
Should the type for parameter $request not be null|StoreRequest?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
91
     *
92
     * @return \Illuminate\Http\RedirectResponse
93
     */
94
    public function storeCrud(StoreRequest $request = null)
95
    {
96
        $this->crud->hasAccessOrFail('create');
97
98
        // fallback to global request instance
99
        if (is_null($request)) {
100
            $request = \Request::instance();
101
        }
102
103
        // replace empty values with NULL, so that it will work with MySQL strict mode on
104 View Code Duplication
        foreach ($request->input() as $key => $value) {
0 ignored issues
show
Bug introduced by
The expression $request->input() of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

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...
105
            if (empty($value) && $value !== '0') {
106
                $request->request->set($key, null);
107
            }
108
        }
109
110
        // insert item in the db
111
        $item = $this->crud->create($request->except(['redirect_after_save', 'password', '_token']));
112
113
        // show a success message
114
        \Alert::success(trans('backpack::crud.insert_success'))->flash();
115
116
        // redirect the user where he chose to be redirected
117
        switch ($request->input('redirect_after_save')) {
118
            case 'current_item_edit':
119
                return \Redirect::to($this->crud->route.'/'.$item->getKey().'/edit');
120
121
            default:
122
                return \Redirect::to($request->input('redirect_after_save'));
0 ignored issues
show
Bug introduced by
It seems like $request->input('redirect_after_save') targeting Illuminate\Http\Request::input() can also be of type array; however, Illuminate\Routing\Redirector::to() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
123
        }
124
    }
125
126
    /**
127
     * Show the form for editing the specified resource.
128
     *
129
     * @param int $id
130
     *
131
     * @return Response
0 ignored issues
show
Documentation introduced by
Should the return type not be \Illuminate\View\View|\I...\Contracts\View\Factory?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
132
     */
133 View Code Duplication
    public function edit($id)
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...
134
    {
135
        $this->crud->hasAccessOrFail('update');
136
137
        // get the info for that entry
138
        $this->data['entry'] = $this->crud->getEntry($id);
139
        $this->data['crud'] = $this->crud;
140
        $this->data['fields'] = $this->crud->getUpdateFields($id);
141
        $this->data['title'] = trans('backpack::crud.edit').' '.$this->crud->entity_name;
142
143
        $this->data['id'] = $id;
144
145
        // load the view from /resources/views/vendor/backpack/crud/ if it exists, otherwise load the one in the package
146
        return view('crud::edit', $this->data);
147
    }
148
149
    /**
150
     * Update the specified resource in the database.
151
     *
152
     * @param UpdateRequest $request - type injection used for validation using Requests
0 ignored issues
show
Documentation introduced by
Should the type for parameter $request not be null|StoreRequest?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
153
     *
154
     * @return \Illuminate\Http\RedirectResponse
155
     */
156
    public function updateCrud(UpdateRequest $request = null)
157
    {
158
        $this->crud->hasAccessOrFail('update');
159
160
        // fallback to global request instance
161
        if (is_null($request)) {
162
            $request = \Request::instance();
163
        }
164
165
        // replace empty values with NULL, so that it will work with MySQL strict mode on
166 View Code Duplication
        foreach ($request->input() as $key => $value) {
0 ignored issues
show
Bug introduced by
The expression $request->input() of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

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...
167
            if (empty($value) && $value !== '0') {
168
                $request->request->set($key, null);
169
            }
170
        }
171
172
        // update the row in the db
173
        $this->crud->update($request->get($this->crud->model->getKeyName()),
0 ignored issues
show
Bug introduced by
The method getKeyName cannot be called on $this->crud->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...
174
                            $request->except('redirect_after_save', '_token'));
175
176
        // show a success message
177
        \Alert::success(trans('backpack::crud.update_success'))->flash();
178
179
        return \Redirect::to($this->crud->route);
180
    }
181
182
    /**
183
     * Display the specified resource.
184
     *
185
     * @param int $id
186
     *
187
     * @return Response
0 ignored issues
show
Documentation introduced by
Should the return type not be \Illuminate\View\View|\I...\Contracts\View\Factory?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
188
     */
189 View Code Duplication
    public function show($id)
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...
190
    {
191
        $this->crud->hasAccessOrFail('show');
192
193
        // get the info for that entry
194
        $this->data['entry'] = $this->crud->getEntry($id);
195
        $this->data['crud'] = $this->crud;
196
        $this->data['title'] = trans('backpack::crud.preview').' '.$this->crud->entity_name;
197
198
        // load the view from /resources/views/vendor/backpack/crud/ if it exists, otherwise load the one in the package
199
        return view('crud::show', $this->data);
200
    }
201
202
    /**
203
     * Display the revisions for specified resource.
204
     *
205
     * @param int $id
206
     *
207
     * @return Response
0 ignored issues
show
Documentation introduced by
Should the return type not be \Illuminate\View\View|\I...\Contracts\View\Factory?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
208
     */
209 View Code Duplication
    public function listRevisions($id)
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...
210
    {
211
        $this->crud->hasAccessOrFail('revisions');
212
213
        // get the info for that entry
214
        $this->data['entry'] = $this->crud->getEntry($id);
215
        $this->data['crud'] = $this->crud;
216
        $this->data['title'] = ucfirst($this->crud->entity_name).' '.trans('backpack::crud.revisions');
217
        $this->data['id'] = $id;
218
        $this->data['revisions'] = $this->crud->listRevisions($id);
219
220
        // load the view from /resources/views/vendor/backpack/crud/ if it exists, otherwise load the one in the package
221
        return view('crud::revisions', $this->data);
222
    }
223
224
    /**
225
     * Restore a specific revision for the specified resource.
226
     *
227
     * Used via AJAX in the revisions view
228
     *
229
     * @param int $id
230
     *
231
     * @return JSON Response containing the new revision that was created from the update
232
     * @return HTTP 500 if the request did not contain the revision ID
0 ignored issues
show
Documentation introduced by
Should the return type not be null|\Illuminate\View\Vi...\Contracts\View\Factory?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
233
     */
234
    public function restoreRevision($id)
235
    {
236
        $this->crud->hasAccessOrFail('revisions');
237
238
        // @TODO: Currently the route already contains the revision ID, so passing it as a POST param
239
        // is somewhat superfluous.. however if we are POSTing, it makes sense to actually have data to post.
240
        // Perhaps the route shoud be better named to reflect this (e.g. just /model/{id}/revisions) (??)
241
        $revisionId = \Request::input('revision_id', false);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|array|null.

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...
242
        if (! $revisionId) {
243
            abort(500, 'Can\'t restore revision without revision_id');
244
        } else {
245
            $this->crud->restoreRevision($id, $revisionId); // do the update
246
247
            $this->data['entry'] = $this->crud->getEntry($id);
248
            $this->data['crud'] = $this->crud;
249
            $this->data['revisions'] = $this->crud->listRevisions($id); // Reload revisions as they have changed
250
251
            // Rebuild the revision timeline HTML and return it to the AJAX call
252
            // @TODO: Return only the latest revision to save bandwidth - 15/9/16 @se1exin
253
            return view('crud::inc.revision_timeline', $this->data);
254
        }
255
    }
256
257
    /**
258
     * Remove the specified resource from storage.
259
     *
260
     * @param int $id
261
     *
262
     * @return string
263
     */
264
    public function destroy($id)
265
    {
266
        $this->crud->hasAccessOrFail('delete');
267
268
        return $this->crud->delete($id);
269
    }
270
271
    /**
272
     *  Reorder the items in the database using the Nested Set pattern.
273
     *
274
     *	Database columns needed: id, parent_id, lft, rgt, depth, name/title
275
     *
276
     *  @return Response
0 ignored issues
show
Documentation introduced by
Should the return type not be \Illuminate\View\View|\I...\Contracts\View\Factory?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
277
     */
278
    public function reorder()
279
    {
280
        $this->crud->hasAccessOrFail('reorder');
281
282
        if (! $this->crud->isReorderEnabled()) {
283
            abort(403, 'Reorder is disabled.');
284
        }
285
286
        // get all results for that entity
287
        $this->data['entries'] = $this->crud->getEntries();
288
        $this->data['crud'] = $this->crud;
289
        $this->data['title'] = trans('backpack::crud.reorder').' '.$this->crud->entity_name;
290
291
        // load the view from /resources/views/vendor/backpack/crud/ if it exists, otherwise load the one in the package
292
        return view('crud::reorder', $this->data);
293
    }
294
295
    /**
296
     * Save the new order, using the Nested Set pattern.
297
     *
298
     * Database columns needed: id, parent_id, lft, rgt, depth, name/title
299
     *
300
     * @return
301
     */
302
    public function saveReorder()
303
    {
304
        $this->crud->hasAccessOrFail('reorder');
305
306
        $all_entries = \Request::input('tree');
307
308
        if (count($all_entries)) {
309
            $count = $this->crud->updateTreeOrder($all_entries);
310
        } else {
311
            return false;
312
        }
313
314
        return 'success for '.$count.' items';
315
    }
316
317
    /**
318
     * Used with AJAX in the list view (datatables) to show extra information about that row that didn't fit in the table.
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 122 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
319
     * It defaults to showing some dummy text.
320
     *
321
     * It's enabled by:
322
     * - setting: $crud->details_row = true;
323
     * - adding the details route for the entity; ex: Route::get('page/{id}/details', 'PageCrudController@showDetailsRow');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 123 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
324
     * - adding a view with the following name to change what the row actually contains: app/resources/views/vendor/backpack/crud/details_row.blade.php
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 151 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
325
     */
326
    public function showDetailsRow($id)
327
    {
328
        $this->crud->hasAccessOrFail('details_row');
329
330
        $this->data['entry'] = $this->crud->getEntry($id);
331
        $this->data['crud'] = $this->crud;
332
333
        // load the view from /resources/views/vendor/backpack/crud/ if it exists, otherwise load the one in the package
334
        return view('crud::details_row', $this->data);
335
    }
336
337
    /**
338
     * Respond with the JSON of one or more rows, depending on the POST parameters.
339
     * @return JSON Array of cells in HTML form.
0 ignored issues
show
Documentation introduced by
Should the return type not be array? Also, consider making the array more specific, something like array<String>, or String[].

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

If the return type contains the type array, this check recommends the use of a more specific type like String[] or array<String>.

Loading history...
340
     */
341
    public function search()
342
    {
343
        $this->crud->hasAccessOrFail('list');
344
345
        // add the primary key, even though you don't show it,
346
        // otherwise the buttons won't work
347
        $columns = collect($this->crud->columns)->pluck('name')->merge($this->crud->model->getKeyName())->toArray();
0 ignored issues
show
Bug introduced by
The method getKeyName cannot be called on $this->crud->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...
348
349
        // structure the response in a DataTable-friendly way
350
        $dataTable = new DataTable($this->crud->query, $columns);
351
352
        // make the datatable use the column types instead of just echoing the text
353
        $dataTable->setFormatRowFunction(function ($entry) {
354
            // get the actual HTML for each row's cell
355
            $row_items = $this->crud->getRowViews($entry, $this->crud);
0 ignored issues
show
Unused Code introduced by
The call to CrudPanel::getRowViews() has too many arguments starting with $this->crud.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
356
357
            // add the buttons as the last column
358
            if ($this->crud->buttons->where('stack', 'line')->count()) {
359
                $row_items[] = \View::make('crud::inc.button_stack', ['stack' => 'line'])
360
                                ->with('crud', $this->crud)
361
                                ->with('entry', $entry)
362
                                ->render();
363
            }
364
365
            // add the details_row buttons as the first column
366
            if ($this->crud->details_row) {
367
                array_unshift($row_items, \View::make('crud::columns.details_row_button')
368
                                ->with('crud', $this->crud)
369
                                ->with('entry', $entry)
370
                                ->render());
371
            }
372
373
            return $row_items;
374
        });
375
376
        return $dataTable->make();
377
    }
378
}
379