Completed
Pull Request — master (#2901)
by
unknown
02:18
created

HasMany::resetInputKey()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 55

Duplication

Lines 26
Ratio 47.27 %

Importance

Changes 0
Metric Value
cc 4
nc 4
nop 2
dl 26
loc 55
rs 8.9818
c 0
b 0
f 0

How to fix   Long Method   

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 Encore\Admin\Form\Field;
4
5
use Encore\Admin\Admin;
6
use Encore\Admin\Form;
7
use Encore\Admin\Form\Field;
8
use Encore\Admin\Form\NestedForm;
9
use Illuminate\Database\Eloquent\Relations\HasMany as Relation;
10
use Illuminate\Database\Eloquent\Relations\MorphMany;
11
use Illuminate\Support\Facades\Validator;
12
use Illuminate\Support\Str;
13
14
/**
15
 * Class HasMany.
16
 */
17
class HasMany extends Field
18
{
19
    /**
20
     * Relation name.
21
     *
22
     * @var string
23
     */
24
    protected $relationName = '';
25
26
    /**
27
     * Form builder.
28
     *
29
     * @var \Closure
30
     */
31
    protected $builder = null;
32
33
    /**
34
     * Form data.
35
     *
36
     * @var array
37
     */
38
    protected $value = [];
39
40
    /**
41
     * View Mode.
42
     *
43
     * Supports `default` and `tab` currently.
44
     *
45
     * @var string
46
     */
47
    protected $viewMode = 'default';
48
49
    /**
50
     * Available views for HasMany field.
51
     *
52
     * @var array
53
     */
54
    protected $views = [
55
        'default' => 'admin::form.hasmany',
56
        'tab'     => 'admin::form.hasmanytab',
57
    ];
58
59
    /**
60
     * Options for template.
61
     *
62
     * @var array
63
     */
64
    protected $options = [
65
        'allowCreate' => true,
66
        'allowDelete' => true,
67
    ];
68
69
    /**
70
     * Create a new HasMany field instance.
71
     *
72
     * @param $relationName
73
     * @param array $arguments
74
     */
75 View Code Duplication
    public function __construct($relationName, $arguments = [])
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...
76
    {
77
        $this->relationName = $relationName;
78
79
        $this->column = $relationName;
80
81
        if (count($arguments) == 1) {
82
            $this->label = $this->formatLabel();
83
            $this->builder = $arguments[0];
84
        }
85
86
        if (count($arguments) == 2) {
87
            list($this->label, $this->builder) = $arguments;
88
        }
89
    }
90
91
    /**
92
     * Get validator for this field.
93
     *
94
     * @param array $input
95
     *
96
     * @return bool|Validator
97
     */
98
    public function getValidator(array $input)
99
    {
100
        if (!array_key_exists($this->column, $input)) {
101
            return false;
102
        }
103
104 View Code Duplication
        $array_key_attach_str = function (array $a, string $b, string $c = '.') {
0 ignored issues
show
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
            return call_user_func_array(
106
                'array_merge',
107
                array_map(function ($u, $v) use ($b, $c) {
108
                    return ["{$b}{$c}{$u}" => $v];
109
                }, array_keys($a), array_values($a))
110
            );
111
        };
112
113 View Code Duplication
        $array_key_clean = function (array $a) {
0 ignored issues
show
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...
114
            $a = count($a) ? call_user_func_array('array_merge', array_map(function ($k, $v) {
115
                return [str_replace(':', '', $k) => $v];
116
            }, array_keys($a), array_values($a))) : $a;
117
118
            return $a;
119
        };
120
121
        $array_clean_merge = function (array $a, $b) {
122
            return array_merge(
123
                $a,
124
                call_user_func_array(
125
                    'array_merge',
126
                    array_filter(
127
                        $b,
128
                        'strlen',
129
                        ARRAY_FILTER_USE_KEY
130
                    )
131
                )
132
            );
133
        };
134
135 View Code Duplication
        $array_key_clean_undot = function (array $a) {
0 ignored issues
show
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...
136
            $keys = preg_grep('/[\.\:]/', array_keys($a));
137
            if ($keys) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $keys of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
138
                foreach ($keys as $key) {
139
                    array_set($a, str_replace(':', '', $key), $a[$key]);
140
                    unset($a[$key]);
141
                }
142
            }
143
144
            return $a;
145
        };
146
147
        $input = array_only($input, $this->column);
148
        $form = $this->buildNestedForm($this->column, $this->builder);
0 ignored issues
show
Bug introduced by
It seems like $this->column can also be of type array; however, Encore\Admin\Form\Field\HasMany::buildNestedForm() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
149
        $rel = $this->relationName;
150
        $rules = $attributes = $messages = $newInputs = [];
151
        // remove all inputs & keys marked as removed
152
        $availInput = array_filter(array_map(function ($v) {
153
            return $v[NestedForm::REMOVE_FLAG_NAME] ? null : $v;
154
        }, $input[$rel]));
155
        $keys = array_keys($availInput);
156
        /* @var Field $field */
157
        foreach ($form->fields() as $field) {
158
            if (!$fieldRules = $field->getRules()) {
159
                continue;
160
            }
161
            $column = $field->column();
162
            $columns = is_array($column) ? $column : [$column];
163 View Code Duplication
            if ($field instanceof Field\MultipleSelect) {
0 ignored issues
show
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...
164
                foreach ($keys as $key) {
165
                    $availInput[$key][$column] = array_filter($availInput[$key][$column], 'strlen') ?: null;
166
                }
167
            }
168
169
            $newColumn = call_user_func_array('array_merge', array_map(function ($u) use ($columns, $rel) {
170
                return array_map(function ($k, $v) use ($u, $rel) {
171
                    //Fix ResetInput Function! A Headache Implementation!
172
                    return $k ? "{$rel}.{$u}.{$v}:{$k}" : "{$rel}.{$u}.{$v}";
173
                }, array_keys($columns), array_values($columns));
174
            }, $keys));
175
176
            $fieldRules = is_array($fieldRules) ? implode('|', $fieldRules) : $fieldRules;
177 View Code Duplication
            $newRules = array_map(function ($v) use ($fieldRules, $availInput, $array_key_attach_str) {
0 ignored issues
show
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...
178
                list($r, $k, $c) = explode('.', $v);
0 ignored issues
show
Unused Code introduced by
The assignment to $r is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
179
                //Fix ResetInput Function! A Headache Implementation!
180
                $col = explode(':', $c)[0];
181
                if (!array_key_exists($col, $availInput[$k])) {
182
                    return [null => null];
183
                }
184
185
                if (is_array($availInput[$k][$col])) {
186
                    return $array_key_attach_str(preg_replace('/./', $fieldRules, $availInput[$k][$col]), $v, ':');
187
                }
188
189
                return [$v => $fieldRules];
190
            }, $newColumn);
191
            $rules = $array_clean_merge($rules, $newRules);
192
193 View Code Duplication
            $newInput = array_map(function ($v) use ($availInput, $array_key_attach_str) {
0 ignored issues
show
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...
194
                list($r, $k, $c) = explode('.', $v);
0 ignored issues
show
Unused Code introduced by
The assignment to $r is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
195
                //Fix ResetInput Function! A Headache Implementation!
196
                $col = explode(':', $c)[0];
197
                if (!array_key_exists($col, $availInput[$k])) {
198
                    return [null => null];
199
                }
200
201
                if (is_array($availInput[$k][$col])) {
202
                    return $array_key_attach_str($availInput[$k][$col], $v, ':');
203
                }
204
205
                return [$v => $availInput[$k][$col]];
206
            }, $newColumn);
207
            $newInputs = $array_clean_merge($newInputs, $newInput);
208
209 View Code Duplication
            $newAttributes = array_map(function ($v) use ($field, $availInput) {
0 ignored issues
show
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...
210
                list($r, $k, $c) = explode('.', $v);
0 ignored issues
show
Unused Code introduced by
The assignment to $r is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
211
                //Fix ResetInput Function! A Headache Implementation!
212
                $col = explode(':', $c)[0];
213
                if (!array_key_exists($col, $availInput[$k])) {
214
                    return [null => null];
215
                }
216
217
                if (is_array($availInput[$k][$col])) {
218
                    return call_user_func_array('array_merge', array_map(function ($u) use ($v, $field) {
219
                        $w = $field->label();
220
                        //Fix ResetInput Function! A Headache Implementation!
221
                        $w .= is_array($field->column()) ? '['.explode(':', explode('.', $v)[2])[0].']' : '';
222
                        return ["{$v}:{$u}" => $w];
223
                    }, array_keys($availInput[$k][$col])));
224
                }
225
226
                $w = $field->label();
227
                //Fix ResetInput Function! A Headache Implementation!
228
                $w .= is_array($field->column()) ? '['.explode(':', explode('.', $v)[2])[0].']' : '';
229
230
                return [$v => $w];
231
            }, $newColumn);
232
            $attributes = $array_clean_merge($attributes, $newAttributes);
233
234 View Code Duplication
            if ($field->validationMessages) {
0 ignored issues
show
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...
235
                $newMessages = array_map(function ($v) use ($field, $availInput, $array_key_attach_str) {
236
                    list($r, $k, $c) = explode('.', $v);
0 ignored issues
show
Unused Code introduced by
The assignment to $r is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
237
                    //Fix ResetInput Function! A Headache Implementation!
238
                    $col = explode(':', $c)[0];
239
                    if (!array_key_exists($col, $availInput[$k])) {
240
                        return [null => null];
241
                    }
242
                    if (is_array($availInput[$k][$col])) {
243
                        return call_user_func_array('array_merge', array_map(function ($u) use ($v, $field, $array_key_attach_str) {
244
                            return $array_key_attach_str($field->validationMessages, "{$v}:{$u}");
245
                        }, array_keys($availInput[$k][$col])));
246
                    }
247
248
                    return $array_key_attach_str($field->validationMessages, $v);
249
                }, $newColumn);
250
                $messages = $array_clean_merge($messages, $newMessages);
251
            }
252
        }
253
254
        $rules = array_filter($rules, 'strlen');
255
        if (empty($rules)) {
256
            return false;
257
        }
258
259
        $attributes = array_filter($attributes, 'strlen');
260
        $messages = array_filter($messages, 'strlen');
261
        $input = $array_key_clean_undot(array_filter($newInputs, 'strlen', ARRAY_FILTER_USE_KEY));
262
        $rules = $array_key_clean($rules);
263
        $attributes = $array_key_clean($attributes);
264
        $messages = $array_key_clean($messages);
265
266
        if (empty($input)) {
267
            $input = [$rel => $availInput];
268
        }
269
270
        return Validator::make($input, $rules, $messages, $attributes);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return \Illuminate\Suppo...messages, $attributes); (Illuminate\Contracts\Validation\Validator) is incompatible with the return type of the parent method Encore\Admin\Form\Field::getValidator of type boolean|Illuminate\Support\Facades\Validator.

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...
271
    }
272
273
    /**
274
     * Prepare input data for insert or update.
275
     *
276
     * @param array $input
277
     *
278
     * @return array
279
     */
280
    public function prepare($input)
281
    {
282
        $form = $this->buildNestedForm($this->column, $this->builder);
0 ignored issues
show
Bug introduced by
It seems like $this->column can also be of type array; however, Encore\Admin\Form\Field\HasMany::buildNestedForm() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
283
284
        return $form->setOriginal($this->original, $this->getKeyName())->prepare($input);
285
    }
286
287
    /**
288
     * Build a Nested form.
289
     *
290
     * @param string   $column
291
     * @param \Closure $builder
292
     * @param null     $key
293
     *
294
     * @return NestedForm
295
     */
296
    protected function buildNestedForm($column, \Closure $builder, $key = null)
297
    {
298
        $form = new Form\NestedForm($column, $key);
299
300
        $form->setForm($this->form);
301
302
        call_user_func($builder, $form);
303
304
        $form->hidden($this->getKeyName());
305
306
        $form->hidden(NestedForm::REMOVE_FLAG_NAME)->default(0)->addElementClass(NestedForm::REMOVE_FLAG_CLASS);
307
308
        return $form;
309
    }
310
311
    /**
312
     * Get the HasMany relation key name.
313
     *
314
     * @return string
315
     */
316
    protected function getKeyName()
317
    {
318
        if (is_null($this->form)) {
319
            return;
320
        }
321
322
        return $this->form->model()->{$this->relationName}()->getRelated()->getKeyName();
323
    }
324
325
    /**
326
     * Set view mode.
327
     *
328
     * @param string $mode currently support `tab` mode.
329
     *
330
     * @return $this
331
     *
332
     * @author Edwin Hui
333
     */
334
    public function mode($mode)
335
    {
336
        $this->viewMode = $mode;
337
338
        return $this;
339
    }
340
341
    /**
342
     * Use tab mode to showing hasmany field.
343
     *
344
     * @return HasMany
345
     */
346
    public function useTab()
347
    {
348
        return $this->mode('tab');
349
    }
350
351
    /**
352
     * Build Nested form for related data.
353
     *
354
     * @throws \Exception
355
     *
356
     * @return array
357
     */
358
    protected function buildRelatedForms()
359
    {
360
        if (is_null($this->form)) {
361
            return [];
362
        }
363
364
        $model = $this->form->model();
365
366
        $relation = call_user_func([$model, $this->relationName]);
367
368
        if (!$relation instanceof Relation && !$relation instanceof MorphMany) {
369
            throw new \Exception('hasMany field must be a HasMany or MorphMany relation.');
370
        }
371
372
        $forms = [];
373
374
        /*
375
         * If redirect from `exception` or `validation error` page.
376
         *
377
         * Then get form data from session flash.
378
         *
379
         * Else get data from database.
380
         */
381
        if ($values = old($this->column)) {
0 ignored issues
show
Bug introduced by
It seems like $this->column can also be of type array; however, old() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
382
            foreach ($values as $key => $data) {
383
                if ($data[NestedForm::REMOVE_FLAG_NAME] == 1) {
384
                    continue;
385
                }
386
387
                $forms[$key] = $this->buildNestedForm($this->column, $this->builder, $key)
0 ignored issues
show
Bug introduced by
It seems like $this->column can also be of type array; however, Encore\Admin\Form\Field\HasMany::buildNestedForm() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
388
                    ->fill($data);
389
            }
390
        } else {
391
            foreach ($this->value as $data) {
392
                $key = array_get($data, $relation->getRelated()->getKeyName());
393
394
                $forms[$key] = $this->buildNestedForm($this->column, $this->builder, $key)
0 ignored issues
show
Bug introduced by
It seems like $this->column can also be of type array; however, Encore\Admin\Form\Field\HasMany::buildNestedForm() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
395
                    ->fill($data);
396
            }
397
        }
398
399
        return $forms;
400
    }
401
402
    /**
403
     * Setup script for this field in different view mode.
404
     *
405
     * @param string $script
406
     *
407
     * @return void
408
     */
409
    protected function setupScript($script)
410
    {
411
        $method = 'setupScriptFor' . ucfirst($this->viewMode) . 'View';
412
413
        call_user_func([$this, $method], $script);
414
    }
415
416
    /**
417
     * Setup default template script.
418
     *
419
     * @param string $templateScript
420
     *
421
     * @return void
422
     */
423 View Code Duplication
    protected function setupScriptForDefaultView($templateScript)
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...
424
    {
425
        $removeClass = NestedForm::REMOVE_FLAG_CLASS;
426
        $defaultKey = NestedForm::DEFAULT_KEY_NAME;
427
428
        /**
429
         * When add a new sub form, replace all element key in new sub form.
430
         *
431
         * @example comments[new___key__][title]  => comments[new_{index}][title]
432
         *
433
         * {count} is increment number of current sub form count.
434
         */
435
        $script = <<<EOT
436
var index = 0;
437
$('#has-many-{$this->column}').on('click', '.add', function() {
438
439
    var tpl = $('template.{$this->column}-tpl');
440
441
    index++;
442
443
    var template = tpl.html().replace(/{$defaultKey}/g, index);
444
    $('.has-many-{$this->column}-forms').append(template);
445
    {$templateScript}
446
});
447
448
$('#has-many-{$this->column}').on('click', '.remove', function() {
449
    $(this).closest('.has-many-{$this->column}-form').hide();
450
    $(this).closest('.has-many-{$this->column}-form').find('.$removeClass').val(1);
451
});
452
453
EOT;
454
455
        Admin::script($script);
456
    }
457
458
    /**
459
     * Setup tab template script.
460
     *
461
     * @param string $templateScript
462
     *
463
     * @return void
464
     */
465 View Code Duplication
    protected function setupScriptForTabView($templateScript)
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...
466
    {
467
        $removeClass = NestedForm::REMOVE_FLAG_CLASS;
468
        $defaultKey = NestedForm::DEFAULT_KEY_NAME;
469
470
        $script = <<<EOT
471
472
$('#has-many-{$this->column} > .nav').off('click', 'i.close-tab').on('click', 'i.close-tab', function(){
473
    var \$navTab = $(this).siblings('a');
474
    var \$pane = $(\$navTab.attr('href'));
475
    if( \$pane.hasClass('new') ){
476
        \$pane.remove();
477
    }else{
478
        \$pane.removeClass('active').find('.$removeClass').val(1);
479
    }
480
    if(\$navTab.closest('li').hasClass('active')){
481
        \$navTab.closest('li').remove();
482
        $('#has-many-{$this->column} > .nav > li:nth-child(1) > a').tab('show');
483
    }else{
484
        \$navTab.closest('li').remove();
485
    }
486
});
487
488
var index = 0;
489
$('#has-many-{$this->column} > .header').off('click', '.add').on('click', '.add', function(){
490
    index++;
491
    var navTabHtml = $('#has-many-{$this->column} > template.nav-tab-tpl').html().replace(/{$defaultKey}/g, index);
492
    var paneHtml = $('#has-many-{$this->column} > template.pane-tpl').html().replace(/{$defaultKey}/g, index);
493
    $('#has-many-{$this->column} > .nav').append(navTabHtml);
494
    $('#has-many-{$this->column} > .tab-content').append(paneHtml);
495
    $('#has-many-{$this->column} > .nav > li:last-child a').tab('show');
496
    {$templateScript}
497
});
498
499
if ($('.has-error').length) {
500
    $('.has-error').parent('.tab-pane').each(function() {
501
        var tabId = '#'+$(this).attr('id');
502
        $('li a[href="'+tabId+'"] i').removeClass('hide');
503
    });
504
    
505
    var first = $('.has-error:first').parent().attr('id');
506
    $('li a[href="#'+first+'"]').tab('show');
507
}
508
EOT;
509
510
        Admin::script($script);
511
    }
512
513
    /**
514
     * Disable create button.
515
     *
516
     * @return $this
517
     */
518
    public function disableCreate()
519
    {
520
        $this->options['allowCreate'] = false;
521
522
        return $this;
523
    }
524
525
    /**
526
     * Disable delete button.
527
     *
528
     * @return $this
529
     */
530
    public function disableDelete()
531
    {
532
        $this->options['allowDelete'] = false;
533
534
        return $this;
535
    }
536
537
    /**
538
     * Render the `HasMany` field.
539
     *
540
     * @throws \Exception
541
     *
542
     * @return \Illuminate\View\View
543
     */
544
    public function render()
545
    {
546
        // specify a view to render.
547
        $this->view = $this->views[$this->viewMode];
548
549
        list($template, $script) = $this->buildNestedForm($this->column, $this->builder)
0 ignored issues
show
Bug introduced by
It seems like $this->column can also be of type array; however, Encore\Admin\Form\Field\HasMany::buildNestedForm() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
550
            ->getTemplateHtmlAndScript();
551
552
        $this->setupScript($script);
553
554
        return parent::render()->with([
0 ignored issues
show
Bug introduced by
The method with does only exist in Illuminate\View\View, but not in Illuminate\Contracts\View\Factory.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
555
            'forms'        => $this->buildRelatedForms(),
556
            'template'     => $template,
557
            'relationName' => $this->relationName,
558
            'options'      => $this->options,
559
        ]);
560
    }
561
}
562