Completed
Push — dev ( 726aeb...0f045d )
by Marc
02:06
created

BaseModelController   B

Complexity

Total Complexity 43

Size/Duplication

Total Lines 320
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 6
Bugs 0 Features 0
Metric Value
wmc 43
c 6
b 0
f 0
lcom 1
cbo 8
dl 0
loc 320
rs 8.3157

16 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 15 4
A checkPermissions() 0 13 1
A handleData() 0 8 1
B getFields() 0 25 4
A getSort() 0 20 3
A getRules() 0 12 3
A getCurrentModelId() 0 4 2
A filterInputData() 0 17 4
A except() 0 10 2
B handleFiles() 0 19 5
A isFileInput() 0 4 2
A uploadFile() 0 18 3
B getRelatedFieldOutput() 0 22 4
A redirect() 0 16 3
A validator() 0 4 1
A all() 0 8 1

How to fix   Complexity   

Complex Class

Complex classes like BaseModelController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use BaseModelController, and based on these observations, apply Extract Interface, too.

1
<?php namespace Mascame\Artificer\Http\Controllers;
2
3
use App;
4
use Auth;
5
use File;
6
use Illuminate\Database\Eloquent\Collection;
7
use Illuminate\Routing\Redirector;
8
use Illuminate\Routing\Router;
9
use Input;
10
use Mascame\Artificer\Fields\FieldFactory;
11
use Mascame\Formality\Parser\Parser;
12
use Mascame\Artificer\Permit\ModelPermit;
13
use Redirect;
14
use Route;
15
use Session;
16
use Validator;
17
use View;
18
19
20
class BaseModelController extends BaseController
21
{
22
23
    /**
24
     * The Eloquent model instance
25
     * @var \Eloquent
26
     */
27
    protected $model;
28
29
    /**
30
     *
31
     */
32
    public function __construct()
33
    {
34
        parent::__construct();
35
36
        // Todo: Do Sth with this
37
        if (false) {
38
            if (! Auth::check() || ! ModelPermit::access()) {
39
                App::abort('403', 'Forbidden access');
40
            }
41
        }
42
43
        $this->model = $this->modelObject->model;
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->modelObject->model of type object<Illuminate\Database\Eloquent\Model> is incompatible with the declared type object<Eloquent> 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...
44
45
        $this->checkPermissions();
46
    }
47
48
    /**
49
     *
50
     */
51
    protected function checkPermissions()
52
    {
53
        $permit = array(
54
            'read' => ModelPermit::to('read'),
55
            'create' => ModelPermit::to('create'),
56
            'update' => ModelPermit::to('update'),
57
            'delete' => ModelPermit::to('delete'),
58
        );
59
60
        ModelPermit::routeAction(Route::currentRouteName());
61
62
        View::share('permit', $permit);
63
    }
64
65
    /**
66
     * @param $data
67
     */
68
    protected function handleData($data)
69
    {
70
        $this->data = $data;
71
72
        $this->getFields($data);
73
74
        View::share('data', $this->data);
75
    }
76
77
    /**
78
     * @param $data
79
     * @return null
80
     */
81
    protected function getFields($data)
0 ignored issues
show
Unused Code introduced by
The parameter $data 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...
82
    {
83
        if ($this->fields) return $this->fields;
84
85
        /**
86
         * @var $data Collection
87
         */
88
        $modelFields = $this->modelObject->getOption('fields');
89
        $fields = [];
90
91
        foreach ($this->modelObject->columns as $column) {
92
            $options = [];
93
94
            if (isset($modelFields[$column])) $options = $modelFields[$column];
95
96
            $fields[$column] = $options;
97
        }
98
99
        $fieldFactory = new FieldFactory(new Parser(config('admin.fields.types')), $fields, config('admin.fields.classmap'));
100
        $this->fields = $fieldFactory->makeFields();
101
102
        View::share('fields', $this->fields);
103
104
        return $this->fields;
105
    }
106
107
    // Prepares fields for factory
108
//    protected function prepareFields($data) {
109
//        $fields = [];
110
//
111
//        foreach ($data as $key => $item) {
112
//            foreach ($this->modelObject->columns as $column) {
113
//                $fields[$key][$column] = $item->$column;
114
//            }
115
//        }
116
//
117
//        return $fields;
118
//    }
119
120
    /**
121
     * @return array
122
     */
123
    protected function getSort()
124
    {
125
        $sort = array();
126
127
        if (Input::has('sort_by')) {
128
            $sort['column'] = Input::get('sort_by');
129
            $sort['direction'] = Input::get('direction');
130
        } else {
131
132
            if ($this->modelObject->schema->hasColumn('sort_id')) {
133
                $sort['column'] = 'sort_id';
134
            } else {
135
                $sort['column'] = 'id';
136
            }
137
138
            $sort['direction'] = 'asc';
139
        }
140
141
        return $sort;
142
    }
143
144
    /**
145
     * @return array
146
     */
147
    protected function getRules()
148
    {
149
        if (isset($this->options['rules'])) {
150
            return $this->options['rules'];
151
        } else {
152
            if (isset($this->model->rules)) {
153
                return $this->model->rules;
154
            }
155
        }
156
157
        return array();
158
    }
159
160
    /**
161
     * @param $items
162
     * @return null
163
     */
164
    public static function getCurrentModelId($items)
165
    {
166
        return (isset($items->id)) ? $items->id : null;
167
    }
168
169
    /**
170
     * @return array|mixed
171
     */
172
    protected function filterInputData()
173
    {
174
        if ($this->modelObject->hasGuarded()) {
175
            $input = Input::all();
176
            $filtered_input = array();
177
178
            foreach ($input as $key => $value) {
179
                if (in_array($key, $this->modelObject->columns)) {
180
                    $filtered_input[$key] = $value;
181
                }
182
            }
183
184
            return $this->except($this->modelObject->getOption('guarded'), $filtered_input);
185
        }
186
187
        return Input::except('id');
188
    }
189
190
    /**
191
     * @param $keys
192
     * @param $values
193
     * @return mixed
194
     */
195
    protected function except($keys, $values)
196
    {
197
        $keys = is_array($keys) ? $keys : func_get_args();
198
199
        $results = $values;
200
201
        array_forget($results, $keys);
202
203
        return $results;
204
    }
205
206
    /**
207
     * @param $data
208
     * @return array
209
     */
210
    protected function handleFiles($data)
211
    {
212
        $new_data = array();
213
        $fields = $this->getFields($data);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $fields is correct as $this->getFields($data) (which targets Mascame\Artificer\Http\C...Controller::getFields()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
214
215
        if (!is_null($fields)) {
216
            foreach ($fields as $field) {
217
                if ($this->isFileInput($field->type)) {
218
                    if (Input::hasFile($field->name)) {
219
                        $new_data[$field->name] = $this->uploadFile($field->name);
220
                    } else {
221
                        unset($data[$field->name]);
222
                    }
223
                }
224
            }
225
        }
226
227
        return array_merge($data, $new_data);
228
    }
229
230
    /**
231
     * @param $type
232
     * @return bool
233
     */
234
    protected function isFileInput($type)
235
    {
236
        return ($type == 'file' || $type == 'image');
237
    }
238
239
    /**
240
     * This is used for simple upload (no plugins)
241
     *
242
     * @param $fieldName
243
     * @param null $path
244
     * @return string
245
     */
246
    protected function uploadFile($fieldName, $path = null)
247
    {
248
        if (!$path) {
249
            $path = public_path() . '/uploads/';
250
        }
251
252
        $file = Input::file($fieldName);
253
254
        if (!file_exists($path)) {
255
            File::makeDirectory($path);
256
        }
257
258
        $name = uniqid() . '-' . Str::slug($file->getFilename()) . '.' . $file->guessExtension();
259
260
        $file->move($path, $name);
261
262
        return $name;
263
    }
264
265
    /**
266
     * @param $modelName
267
     * @param $id
268
     * @param $field
269
     * @return null
270
     */
271
    protected function getRelatedFieldOutput($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...
272
    {
273
        if ($id != 0) {
274
            $this->handleData($this->model->with($this->modelObject->getRelations())->findOrFail($id));
275
        } else {
276
            if (Session::has('_set_relation_on_create_' . $this->modelObject->name)) {
277
                $relateds = Session::get('_set_relation_on_create_' . $this->modelObject->name);
278
                $related_ids = array();
279
                foreach ($relateds as $related) {
280
                    $related_ids[] = $related['id'];
281
                }
282
283
                $data = $relateds[0]['modelClass']::whereIn('id', $related_ids)->get();
284
285
                $this->handleData($data);
286
            } else {
287
                return null;
288
            }
289
        }
290
291
        return $this->fields[$field]->output();
292
    }
293
294
    /**
295
     * @param $validator
296
     * @param string $route
297
     * @return $this
298
     */
299
    protected function redirect($validator, $route, $id = null)
300
    {
301
        if (Input::has('_standalone')) {
302
            $routeParams = array('slug' => Input::get('_standalone'));
303
304
            if ($id) {
305
                $routeParams['id'] = $id;
306
            }
307
308
            return Redirect::route($route, $routeParams)
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...
309
                ->withErrors($validator)
310
                ->withInput();
311
        }
312
313
        return Redirect::back()->withErrors($validator)->withInput();
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...
314
    }
315
316
    /**
317
     * @param $data
318
     * @return \Illuminate\Validation\Validator
319
     */
320
    protected function validator($data)
321
    {
322
        return Validator::make($data, $this->getRules());
323
    }
324
325
    /**
326
     * @param $modelName
327
     * @param null $data
328
     * @param $sort
329
     * @return $this
330
     */
331
    protected function all($modelName, $data = null, $sort)
332
    {
333
        $this->handleData($data);
334
335
        return View::make($this->getView('all'))
336
            ->with('items', $this->data)
337
            ->with('sort', $sort);
338
    }
339
}