NestedModelsCrudController::storeCrud()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 0
cts 5
cp 0
rs 9.8666
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 6
1
<?php
2
3
namespace Webfactor\Laravel\Backpack\NestedModels\Controllers;
4
5
use Backpack\CRUD\app\Http\Controllers\CrudController;
6
use Backpack\CRUD\app\Http\Requests\CrudRequest as StoreRequest;
7
use Illuminate\Http\Request;
8
9
class NestedModelsCrudController extends CrudController
10
{
11
    public function treeSetup()
12
    {
13
        $this->crud->setListView('nestedmodels::treecrud');
14
        $this->crud->orderBy('lft');
15
16
        $this->crud->allowAccess('reorder');
17
    }
18
19
    public function index()
20
    {
21
        $this->crud->hasAccessOrFail('list');
22
23
        $this->data['crud'] = $this->crud;
24
        $this->data['title'] = ucfirst($this->crud->entity_name_plural);
25
26
        $entries = $this->data['crud']->getEntries();
27
        $this->data['entries'] = $this->crud->model::loadTree($entries);
0 ignored issues
show
Bug introduced by
The method loadTree 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...
28
29
        return view($this->crud->getListView(), $this->data);
0 ignored issues
show
Bug Compatibility introduced by
The expression view($this->crud->getListView(), $this->data); of type Illuminate\View\View|Ill...\Contracts\View\Factory adds the type Illuminate\Contracts\View\Factory to the return on line 29 which is incompatible with the return type of the parent method Backpack\CRUD\app\Http\C...s\CrudController::index of type Illuminate\View\View.
Loading history...
30
    }
31
32
    public function create()
33
    {
34
        $request = \Request::instance();
35
36
        if ($parent = $request->get('parent')) {
37
            $this->crud->addField([
38
                'name'  => 'parent_id',
39
                'type'  => 'hidden',
40
                'value' => $parent
41
            ]);
42
        }
43
44
        if ($request->wantsJson()) {
45
            return $this->ajaxCreate($request);
46
        }
47
48
        return parent::create();
49
    }
50
51
    public function ajaxCreate(Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request 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...
52
    {
53
        $this->crud->hasAccessOrFail('create');
54
55
        // prepare the fields you need to show
56
        $this->data['crud'] = $this->crud;
57
        $this->data['saveAction'] = $this->getSaveAction();
58
        $this->data['fields'] = $this->crud->getCreateFields();
59
        $this->data['title'] = trans('backpack::crud.add').' '.$this->crud->entity_name;
60
61
        // load the view from /resources/views/vendor/backpack/crud/ if it exists, otherwise load the one in the package
62
        return view('nestedmodels::ajax.create', $this->data);
63
    }
64
65
    public function storeCrud(StoreRequest $request = null)
66
    {
67
        if ($request->wantsJson()) {
0 ignored issues
show
Bug introduced by
It seems like $request is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
68
            return $this->ajaxStore($request);
0 ignored issues
show
Bug introduced by
It seems like $request defined by parameter $request on line 65 can be null; however, Webfactor\Laravel\Backpa...Controller::ajaxStore() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
Bug Best Practice introduced by
The return type of return $this->ajaxStore($request); (Illuminate\Database\Eloquent\Model) is incompatible with the return type of the parent method Backpack\CRUD\app\Http\C...udController::storeCrud of type Illuminate\Http\RedirectResponse.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
69
        }
70
71
        // your additional operations before save here
72
        $redirect_location = parent::storeCrud($request);
73
        // your additional operations after save here
74
        // use $this->data['entry'] or $this->crud->entry
75
        return $redirect_location;
76
    }
77
78
    public function ajaxStore(StoreRequest $request)
79
    {
80
        $this->crud->hasAccessOrFail('create');
81
82
        // fallback to global request instance
83
        if (is_null($request)) {
84
            $request = \Request::instance();
85
        }
86
87
        // replace empty values with NULL, so that it will work with MySQL strict mode on
88
        foreach ($request->input() as $key => $value) {
0 ignored issues
show
Bug introduced by
The expression $request->input() of type string|array|null 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...
89
            if (empty($value) && $value !== '0') {
90
                $request->request->set($key, null);
91
            }
92
        }
93
94
        // insert item in the db
95
        return $this->crud->create($request->except(['save_action', '_token', '_method']));
96
    }
97
98
    public function saveReorder()
99
    {
100
        $this->crud->hasAccess('reorder');
101
        $request = \Request::instance();
102
103
        $this->crud->model::rebuildTree($request->all());
0 ignored issues
show
Bug introduced by
The method rebuildTree 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...
104
105
        return (string) true;
106
    }
107
}
108