Completed
Push — dev ( c4383c...9ff19d )
by Marc
02:13
created

ModelController::updateOrCreate()   B

Complexity

Conditions 6
Paths 12

Size

Total Lines 41
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 41
rs 8.439
cc 6
eloc 22
nc 12
nop 2
1
<?php namespace Mascame\Artificer\Controllers;
2
3
use Input;
4
use Mascame\Artificer\Options\AdminOption;
5
use Redirect;
6
use Request;
7
use Response;
8
use URL;
9
use View;
10
11
class ModelController extends BaseModelController
12
{
13
14
    /**
15
     * Show the form for creating a new resource.
16
     *
17
     * @return Response
18
     */
19
    public function create()
20
    {
21
        $this->handleData($this->modelObject->schema->getInstance());
22
23
        $form = array(
24
            'form_action_route' => 'admin.model.store',
25
            'form_method' => 'post'
26
        );
27
28
        return View::make($this->getView('edit'))->with('items', $this->data)->with($form);
29
    }
30
31
    /**
32
     * @param $modelName
33
     * @return $this
34
     */
35
    public function filter($modelName)
36
    {
37
        $this->handleData($this->model->firstOrFail());
38
39
        $sort = $this->getSort();
40
41
        $data = $this->model->where(function ($query) {
42
43
            foreach (\Request::all() as $name => $value) {
44
                if ($value != '' && isset($this->fields[$name])) {
45
                    $this->fields[$name]->filter($query, $value);
46
                }
47
            }
48
49
            return null;
50
        })
51
            ->with($this->modelObject->getRelations())
52
            ->orderBy($sort['column'], $sort['direction'])
53
            ->get();
54
55
        return parent::all($modelName, $data, $sort);
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (all() instead of filter()). Are you sure this is correct? If so, you might want to change this to $this->all().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
56
    }
57
58
    /**
59
     * Display the specified resource.
60
     *
61
     * @param  int $id
62
     * @return Response
63
     */
64
    public function show($modelName, $id)
0 ignored issues
show
Unused Code introduced by
The parameter $modelName 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...
65
    {
66
        $this->handleData($this->model->findOrFail($id));
67
68
        return View::make($this->getView('show'))->with('item', $this->data);
69
    }
70
71
    /**
72
     * Display the specified post.
73
     *
74
     * @return Response
75
     */
76
    public function all($modelName, $data = null, $sort = null)
77
    {
78
        $sort = $this->getSort();
79
80
        $data = $this->model->with($this->modelObject->getRelations())->orderBy($sort['column'],
81
            $sort['direction'])->get();
82
83
        return parent::all($modelName, $data, $sort);
84
    }
85
86
    /**
87
     * Show the form for editing the specified post.
88
     *
89
     * @param  int $id
90
     * @return Response
91
     */
92
    public function edit($modelName, $id)
0 ignored issues
show
Unused Code introduced by
The parameter $modelName 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...
93
    {
94
        $this->handleData(
95
            $this->model->with($this->modelObject->getRelations())->findOrFail($id)
96
        );
97
98
        $form = array(
99
            'form_action_route' => 'admin.model.update',
100
            'form_method' => 'put'
101
        );
102
103
        return View::make($this->getView('edit'))
104
            ->with('items', $this->data)
105
            ->with($form);
106
    }
107
108
    public function field($modelName, $id, $field)
0 ignored issues
show
Unused Code introduced by
The parameter $modelName 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...
109
    {
110
        $this->handleData($this->model->with($this->modelObject->getRelations())->findOrFail($id));
111
112
        $this->fields[$field]->showFullField = true;
113
114
        return \HTML::field($this->fields[$field], AdminOption::get('icons'));
115
    }
116
117
    protected function handleAjaxResponse($item)
118
    {
119
        return Response::json(array(
120
                'item' => $item->toArray(),
121
                'refresh' => URL::route('admin.model.field.edit', array(
122
                    'slug' => Input::get('_standalone_origin'),
123
                    'id' => Input::get('_standalone_origin_id'),
124
                    'field' => ':fieldName:'
125
                ))
126
            )
127
        );
128
    }
129
130
    /**
131
     * Update or create the specified resource in storage.
132
     *
133
     * @param  int $id
134
     * @return Response
135
     */
136
137
    public function updateOrCreate($modelName, $id = null)
0 ignored issues
show
Unused Code introduced by
The parameter $modelName 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...
138
    {
139
        $isUpdating = $id;
140
        $item = null;
141
142
        if ($isUpdating) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $isUpdating of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
143
            $item = $this->model->findOrFail($id);
144
        }
145
146
        $data = $this->filterInputData();
147
148
        $validator = $this->validator($data);
149
150
        if ($validator->fails()) {
151
152
            if ($isUpdating) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $isUpdating of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
153
                return $this->redirect($validator, 'admin.model.edit', $id);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->redirect($...dmin.model.edit', $id); (redirect) is incompatible with the return type documented by Mascame\Artificer\Contro...troller::updateOrCreate of type Illuminate\Contracts\Routing\ResponseFactory.

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...
154
            } else {
155
                return $this->redirect($validator, 'admin.model.create');
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->redirect($... 'admin.model.create'); (redirect) is incompatible with the return type documented by Mascame\Artificer\Contro...troller::updateOrCreate of type Illuminate\Contracts\Routing\ResponseFactory.

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...
156
            }
157
        }
158
159
        $this->model->guard($this->modelObject->getGuarded());
160
        $this->model->fillable($this->modelObject->getOption('fillable', []));
161
162
        //        $this->handleData($data);
163
164
        $data = $this->handleFiles($data);
165
166
        if ($isUpdating) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $isUpdating of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
167
            $item->update($data);
168
        } else {
169
            $item = $this->model->create($data);
170
        }
171
172
        if (Request::ajax()) {
173
            return $this->handleAjaxResponse($item);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->handleAjaxResponse($item); (Illuminate\Http\JsonResponse) is incompatible with the return type documented by Mascame\Artificer\Contro...troller::updateOrCreate of type Illuminate\Contracts\Routing\ResponseFactory.

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...
174
        }
175
176
        return Redirect::route('admin.model.all', array('slug' => $this->modelObject->getRouteName()));
0 ignored issues
show
Bug introduced by
The method route() does not seem to exist on object<redirect>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
177
    }
178
179
    /**
180
     * Remove the specified resource from storage.
181
     *
182
     * @param $modelName
183
     * @param $id
184
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
185
     */
186
    public function destroy($modelName, $id)
0 ignored issues
show
Unused Code introduced by
The parameter $modelName 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...
187
    {
188
        if ($this->model->destroy($id)) {
189
            // Todo Notify::success('<b>Success!</b> The record has been deleted!', true);
190
        } else {
191
            // Todo Notify::danger('<b>Failed!</b> The record could not be deleted!');
192
        }
193
194
        return Request::ajax() ? \Response::json([]) : Redirect::back();
0 ignored issues
show
Bug introduced by
The method back() does not seem to exist on object<redirect>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
195
    }
196
197
}