Completed
Push — master ( 9fc61c...5a9a08 )
by David
07:40
created

CrudApi::renderFields()   D

Complexity

Conditions 10
Paths 14

Size

Total Lines 37
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 37
rs 4.8196
cc 10
eloc 28
nc 14
nop 2

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Taskforcedev\CrudApi\Helpers;
4
5
use Illuminate\Console\DetectsApplicationNamespace;
6
7
class CrudApi
8
{
9
    use DetectsApplicationNamespace;
10
11
    public $model;
12
    public $instance;
13
    public $namespace;
14
    public $modelHelper;
15
    public $fieldHelper;
16
17
    /**
18
     * CrudApi Helper.
19
     * @param array $options
20
     */
21
    public function __construct($options = [])
22
    {
23
        /* Set the namespace */
24
        if (array_key_exists('namespace', $options)) {
25
            $this->namespace = $options['namespace'];
26
        } else {
27
            $this->namespace = $this->getAppNamespace();
28
        }
29
30
        /* Set the model */
31
        if (array_key_exists('model', $options)) {
32
            $this->model = $options['model'];
33
        }
34
35
        $this->modelHelper = new Model($this);
36
        $this->fieldHelper = new Field($this);
37
    }
38
39
    /**
40
     * Set the Crud API Model Helper.
41
     * @param object $modelHelper Model Helper Object.
42
     */
43
    public function setModelHelper($modelHelper)
44
    {
45
        $this->modelHelper = $modelHelper;
46
    }
47
48
    /**
49
     * Set the namespace to search within.
50
     *
51
     * @param string $namespace
52
     */
53
    public function setNamespace($namespace)
54
    {
55
        $this->namespace = $namespace;
56
    }
57
58
    /**
59
     * Set the model to work with.
60
     *
61
     * @param string $model Model name.
62
     *
63
     * @return $this
64
     */
65
    public function setModel($model)
66
    {
67
        $this->model = $model;
68
69
        return $this;
70
    }
71
72
    /**
73
     * Set a model instance from which to work.
74
     *
75
     * @param Object $item Model instance
76
     *
77
     * @return $this
78
     */
79
    public function setInstance($item)
80
    {
81
        $this->instance = $item;
82
83
        return $this;
84
    }
85
86
    /**
87
     * Get Fields
88
     *
89
     * Get a models fillable fields.
90
     *
91
     * @return array
92
     */
93
    public function getFields()
94
    {
95
        $model = $this->getModelInstance();
96
        $fields = $model->getFillable();
97
        $filtered_fields = [];
98
99
        foreach ($fields as $f) {
100
            if ($f !== 'password' && $f !== 'Password') {
101
                $filtered_fields[] = $f;
102
            }
103
        }
104
105
        return $filtered_fields;
106
    }
107
108
    /**
109
     * Get a models display name.
110
     * @return string
111
     */
112
    public function getModelDisplayName()
113
    {
114
        $instance = $this->getModelInstance();
115
        $display = isset($instance->display) ? $instance->display : ucfirst($this->model);
116
117
        return $display;
118
    }
119
120
    /**
121
     * Get an instance of a model.
122
     * @return bool
123
     */
124
    public function getModelInstance()
125
    {
126
        if ($this->instance !== null) {
127
            return $this->instance;
128
        }
129
        $model = $this->getModel();
130
        if ($model === false) {
131
            return false;
132
        }
133
        $instance = new $model();
134
135
        return $instance;
136
    }
137
138
    /**
139
     * Generate a modal for a model.
140
     * @param string $type Modal type (edit, create, delete).
141
     * @return object
142
     */
143
    public function modal($type)
144
    {
145
        $trimmed_item = $this->trimmedModel();
146
147
        $modalId = $type.$trimmed_item.'Modal';
148
149
        $display = $this->getModelDisplayName();
150
151
        $modal = (object) [
152
            'id' => $modalId,
153
            'title' => ucfirst($type).' '.$display,
154
            'url' => $this->modalUrl($type),
155
        ];
156
157
        return $modal;
158
    }
159
160
    /**
161
     * Get the modals url.
162
     *
163
     * @param $type
164
     *
165
     * @return string
166
     */
167
    private function modalUrl($type)
168
    {
169
        switch ($type) {
170
        case 'edit':
171
            $action = 'update';
172
            break;
173
        default:
174
            $action = $type;
175
            break;
176
        }
177
178
        return route('crudapi.'.$action.'.item', $this->model);
0 ignored issues
show
Documentation introduced by
$this->model is of type string, but the function expects a array.

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...
179
    }
180
181
    /**
182
     * Get the name of the javascript method for a model.
183
     *
184
     * @param $method
185
     *
186
     * @return string
187
     */
188
    public function jsMethodName($method)
189
    {
190
        // Method == create
191
        $jsMethod = $method.$this->trimmedModel();
192
193
        return $jsMethod;
194
    }
195
196
    /**
197
     * Render fields.
198
     * @param $type
199
     * @param array $fields
200
     */
201
    public function renderFields($type, $fields = [])
202
    {
203
        if (empty($fields)) {
204
            $fields = $this->getFields();
205
        }
206
        $output = '';
207
208
        switch ($type) {
209
        case 'form-create':
210
            $output .= $this->fieldHelper->formCreate($fields);
211
            break;
212
        case 'form-edit':
213
            $output .= $this->fieldHelper->formEdit($fields);
214
            break;
215
        case 'table-headings':
216
            $output .= $this->fieldHelper->tableHeadings($fields);
217
            break;
218
        case 'table-content':
219
            $output .= $this->fieldHelper->tableContent($fields, $this->instance);
220
            break;
221
            // JavaScript Variables
222
        case 'js-var':
223
            foreach ($fields as $f) {
224
                $output .= 'var '.$f.' = '.$this->instance->$f.'; ';
225
            }
226
            break;
227
        case 'js-modal-create':
228
            foreach ($fields as $f) {
229
                $output .= '"'.$f.'": $(\'#createItem'.$f.'\').val(), ';
230
            }
231
            break;
232
        default:
233
            break;
234
        }
235
236
        echo $output;
237
    }
238
239
    public function trimmedModel()
240
    {
241
        return strpos($this->model, ' ') !== false ? implode('', explode(' ', $this->model)) : $this->model;
242
    }
243
244
    public function getRelatedOptions($relation)
245
    {
246
        $output = '';
247
248
        if (!method_exists($relation, 'toOptions')) {
249
            $relationItems = $relation::all();
250
            foreach ($relationItems as $item) {
251
                if (isset($item->name)) {
252
                    $output .= '<option value="'.$item->id.'">'.$item->name.'</option>';
253
                }
254
            }
255
        } else {
256
            $output .= $relation->toOptions();
257
        }
258
259
        return $output;
260
    }
261
262
    public function getRelatedModel($f)
263
    {
264
        $field = $this->getRelatedField($f);
0 ignored issues
show
Documentation Bug introduced by
The method getRelatedField does not exist on object<Taskforcedev\CrudApi\Helpers\CrudApi>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
265
        $model = $this->getModel($field);
0 ignored issues
show
Bug introduced by
The method getModel() does not exist on Taskforcedev\CrudApi\Helpers\CrudApi. Did you maybe mean getModelDisplayName()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
266
267
        $modelAliases = [
268
            'author' => 'user',
269
        ];
270
271
        // If class doesn't exist, check if is in aliases array.
272
        if (!class_exists($model)) {
273
            if (array_key_exists($field, $modelAliases)) {
274
                $aliasedModel = $modelAliases[$field];
275
                $model = $this->getModel($aliasedModel);
0 ignored issues
show
Bug introduced by
The method getModel() does not exist on Taskforcedev\CrudApi\Helpers\CrudApi. Did you maybe mean getModelDisplayName()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
276
            }
277
        }
278
279
        // Model could not be found, try via it's converted name.
280
        if (!class_exists($model)) {
281
            // Convert from DB format to Pascal
282
            $words = explode('_', $field);
283
            foreach ($words as $i => $w) {
284
                $words[$i] = ucfirst($w);
285
            }
286
            $formatted = implode('', $words);
287
            $model = 'App\\'.$formatted;
288
            if (!class_exists($model)) {
289
                return false;
290
            }
291
        }
292
293
        return new $model();
294
    }
295
296
    public function getRelatedDisplay($f)
297
    {
298
        $related_field = $this->getRelatedField($f);
0 ignored issues
show
Documentation Bug introduced by
The method getRelatedField does not exist on object<Taskforcedev\CrudApi\Helpers\CrudApi>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
299
300
        $field = $this->instance->$related_field;
301
302
        $class = get_class($field);
303
304
        switch ($class) {
305
        case 'App\\Helpers\\CrudApi':
306
            break;
307
        case 'App\\Indicator':
308
            return $field->indicator;
309
                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...
310
        case 'Taskforcedev\\CrudApi\\Helpers\\CrudApi':
311
            return false;
312
        default:
313
            return $field->name;
314
        }
315
    }
316
317
    /**
318
     * Allow certain methods to be passed through to the specified
319
     * helper in order to make methods easier to remember.
320
     *
321
     * @param $method
322
     * @param $args
323
     *
324
     * @method string getRelatedField
325
     * @method string getPrimaryField
326
     * @method bool isIdField
327
     * @method mixed getModel
328
     *
329
     * @return bool
330
     */
331
    public function __call($method, $args)
332
    {
333
        switch ($method) {
334
            case 'getRelatedField':
335
                return $this->fieldHelper->getRelatedField($args[0]);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->fieldHelpe...RelatedField($args[0]); (string) is incompatible with the return type documented by Taskforcedev\CrudApi\Helpers\CrudApi::__call of type boolean.

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...
336
            case 'getPrimaryField':
337
                return $this->fieldHelper->getPrimaryField($args[0]);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->fieldHelpe...PrimaryField($args[0]); (string) is incompatible with the return type documented by Taskforcedev\CrudApi\Helpers\CrudApi::__call of type boolean.

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...
338
            case 'isIdField':
339
                return $this->fieldHelper->isIdField($args[0]);
340
            case 'getModel':
341
                if (isset($args[0])) {
342
                    return $this->modelHelper->getModel($args[0]);
343
                }
344
                return $this->modelHelper->getModel();
345
            default:
346
                break;
347
        }
348
    }
349
}
350