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

HasMany::getValidator()   F

Complexity

Conditions 29
Paths 55

Size

Total Lines 184

Duplication

Lines 57
Ratio 30.98 %

Importance

Changes 0
Metric Value
cc 29
nc 55
nop 1
dl 57
loc 184
rs 3.3333
c 0
b 0
f 0

How to fix   Long Method    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 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 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...
122
            if (count($a)) {
123
                foreach ($a as $key => $val) {
124
                    array_set($a, str_replace(':', '', $key), $val);
125
                    if (preg_match('/[\.\:]/', $key)) {
126
                        unset($a[$key]);
127
                    }
128
                }
129
            }
130
131
            return $a;
132
        };
133
134
        $input = array_only($input, $this->column);
135
        $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...
136
        $rel = $this->relationName;
137
        $rules = $attributes = [];
138
        $messages = [];
139
        // remove all inputs & keys marked as removed
140
        $availInput = array_filter(array_map(function ($v) {
141
            return $v[NestedForm::REMOVE_FLAG_NAME] ? null : $v;
142
        }, $input[$rel]));
143
        $keys = array_keys($availInput);
144
        /* @var Field $field */
145
        foreach ($form->fields() as $field) {
146
            if (!$fieldRules = $field->getRules()) {
147
                continue;
148
            }
149
            $column = $field->column();
150
            $columns = is_array($column) ? $column : [$column];
151
            if ($field instanceof Field\MultipleSelect) {
152
                foreach ($keys as $key) {
153
                    $availInput[$key][$column] = array_filter($availInput[$key][$column], 'strlen');
154
                    $availInput[$key][$column] = $availInput[$key][$column] ?: null;
155
                }
156
            }
157
            // if($field instanceof Field\File)
158
            // {
159
            //     dd(request());
160
            // }
161
            $newColumn = call_user_func_array('array_merge', array_map(function ($u) use ($columns, $rel) {
162
                return array_map(function ($k, $v) use ($u, $rel) {
163
                    //Fix ResetInput Function! A Headache Implementation!
164
                    return !$k ? "{$rel}.{$u}.{$v}" : "{$rel}.{$u}.{$v}:{$k}";
165
                }, array_keys($columns), array_values($columns));
166
            }, $keys));
167
168
            $fieldRules = is_array($fieldRules) ? implode('|', $fieldRules) : $fieldRules;
169
            $rules = array_merge($rules, call_user_func_array(
170
                'array_merge',
171
                array_map(function ($v) use ($fieldRules) {
172
                    return [$v => $fieldRules];
173
                }, $newColumn)
174
            ));
175
            $attributes = array_merge($attributes, call_user_func_array(
176
                'array_merge',
177 View Code Duplication
                array_map(function ($v) use ($field) {
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
                    //Fix ResetInput Function! A Headache Implementation!
179
                    $u = $field->label();
180
                    $u .= is_array($field->column()) ? '['.explode(':', explode('.', $v)[1])[0].']' : '';
181
182
                    return [$v => "{$u}"];
183
                }, $newColumn)
184
            ));
185 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...
186
                $newMessages = array_map(function ($v) use ($field, $availInput, $array_key_attach_str) {
187
                    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...
188
                    //Fix ResetInput Function! A Headache Implementation!
189
                    $col1 = explode(':', $c)[0];
190
                    if (!array_key_exists($col1, $availInput[$k])) {
191
                        return [null => null];
192
                    }
193
                    $rows = $availInput[$k][$col1];
194
                    if (!is_array($rows)) {
195
                        return $array_key_attach_str($field->validationMessages, $v);
196
                    }
197
                    $r = [];
198
                    foreach (array_keys($rows) as $k) {
199
                        $k = "{$v}{$k}";
200
                        $r = array_merge($r, $array_key_attach_str($field->validationMessages, $k));
201
                    }
202
203
                    return $r;
204
                }, $newColumn);
205
                $newMessages = call_user_func_array('array_merge', $newMessages);
206
                $messages = array_merge($messages, $newMessages);
207
            }
208
        }
209
210
        if (empty($rules)) {
211
            return false;
212
        }
213
214
        $newInput = call_user_func_array('array_merge', array_map(function ($u) use ($availInput) {
215
            list($rel, $key, $col) = explode('.', $u);
216
            $idx = "{$rel}.{$key}.{$col}";
217
            //Fix ResetInput Function! A Headache Implementation!
218
            $col1 = explode(':', $col)[0];
219
            if (!array_key_exists($col1, $availInput[$key])) {
220
                return [null => null];
221
            }
222
            if (is_array($availInput[$key][$col1])) {
223
                return call_user_func_array('array_merge', array_map(function ($x, $y) use ($idx) {
224
                    return ["{$idx}{$x}" => $y];
225
                }, array_keys($availInput[$key][$col1]), $availInput[$key][$col1]));
226
            }
227
228
            return ["{$idx}" => $availInput[$key][$col1]];
229
        }, array_keys($rules)));
230
        $newInput = $array_key_clean_undot($newInput);
231
232
        $newRules = array_map(function ($u) use ($availInput, $rules) {
233
            list($rel, $key, $col) = explode('.', $u);
234
            $idx = "{$rel}.{$key}.{$col}";
235
            //Fix ResetInput Function! A Headache Implementation!
236
            $col1 = explode(':', $col)[0];
237
            if (!array_key_exists($col1, $availInput[$key])) {
238
                return [null => null];
239
            }
240
            if (is_array($availInput[$key][$col1])) {
241
                return call_user_func_array('array_merge', array_map(function ($x) use ($idx, $rules) {
242
                    return ["{$idx}{$x}" => $rules[$idx]];
243
                }, array_keys($availInput[$key][$col1])));
244
            }
245
246
            return ["{$idx}" => $rules[$idx]];
247
        }, array_keys($rules));
248
        $newRules = array_filter(call_user_func_array('array_merge', $newRules), 'strlen', ARRAY_FILTER_USE_KEY);
249
        $newRules = $array_key_clean($newRules);
250
251
        $newAttributes = array_map(function ($u) use ($availInput, $attributes) {
252
            list($rel, $key, $col) = explode('.', $u);
253
            $idx = "{$rel}.{$key}.{$col}";
254
            //Fix ResetInput Function! A Headache Implementation!
255
            $col1 = explode(':', $col)[0];
256
            if (!array_key_exists($col1, $availInput[$key])) {
257
                return [null => null];
258
            }
259 View Code Duplication
            if (is_array($availInput[$key][$col1])) {
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...
260
                if (array_keys($availInput[$key][$col1])) {
261
                    return call_user_func_array('array_merge', array_map(function ($x) use ($idx, $attributes) {
262
                        return ["{$idx}.{$x}" => $attributes[$idx]];
263
                    }, array_keys($availInput[$key][$col1])));
264
                }
265
266
                return [null => null];
267
            }
268
269
            return ["{$idx}" => $attributes[$idx]];
270
        }, array_keys($attributes));
271
        $newAttributes = array_filter(call_user_func_array('array_merge', $newAttributes), 'strlen');
272
        $newAttributes = $array_key_clean($newAttributes);
273
274
        $messages = $array_key_clean($messages);
275
276
        if (empty($newInput)) {
277
            $newInput = [$rel => $availInput];
278
        }
279
280
        return Validator::make($newInput, $newRules, $messages, $newAttributes);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return \Illuminate\Suppo...sages, $newAttributes); (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...
281
    }
282
283
    /**
284
     * Format validation attributes.
285
     *
286
     * @param array  $input
287
     * @param string $label
288
     * @param string $column
289
     *
290
     * @return array
291
     */
292 View Code Duplication
    protected function formatValidationAttribute($input, $label, $column)
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...
293
    {
294
        $new = $attributes = [];
295
296
        if (is_array($column)) {
297
            foreach ($column as $index => $col) {
298
                $new[$col.$index] = $col;
299
            }
300
        }
301
302
        foreach (array_keys(array_dot($input)) as $key) {
303
            if (is_string($column)) {
304
                if (Str::endsWith($key, ".$column")) {
305
                    $attributes[$key] = $label;
306
                }
307
            } else {
308
                foreach ($new as $k => $val) {
309
                    if (Str::endsWith($key, ".$k")) {
310
                        $attributes[$key] = $label."[$val]";
311
                    }
312
                }
313
            }
314
        }
315
316
        return $attributes;
317
    }
318
319
    /**
320
     * Reset input key for validation.
321
     *
322
     * @param array $input
323
     * @param array $column $column is the column name array set
324
     *
325
     * @return void.
0 ignored issues
show
Documentation introduced by
The doc-type void. could not be parsed: Unknown type name "void." at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
326
     */
327
    protected function resetInputKey(array &$input, array $column)
328
    {
329
        /**
330
         * flip the column name array set.
331
         *
332
         * for example, for the DateRange, the column like as below
333
         *
334
         * ["start" => "created_at", "end" => "updated_at"]
335
         *
336
         * to:
337
         *
338
         * [ "created_at" => "start", "updated_at" => "end" ]
339
         */
340
        $column = array_flip($column);
341
342
        /**
343
         * $this->column is the inputs array's node name, default is the relation name.
344
         *
345
         * So... $input[$this->column] is the data of this column's inputs data
346
         *
347
         * in the HasMany relation, has many data/field set, $set is field set in the below
348
         */
349
        foreach ($input[$this->column] as $index => $set) {
350
            /*
351
             * foreach the field set to find the corresponding $column
352
             */
353 View Code Duplication
            foreach ($set as $name => $value) {
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...
354
                /*
355
                 * if doesn't have column name, continue to the next loop
356
                 */
357
                if (!array_key_exists($name, $column)) {
358
                    continue;
359
                }
360
361
                /**
362
                 * example:  $newKey = created_atstart.
363
                 *
364
                 * Σ( ° △ °|||)︴
365
                 *
366
                 * I don't know why a form need range input? Only can imagine is for range search....
367
                 */
368
                $newKey = $name.$column[$name];
369
370
                /*
371
                 * set new key
372
                 */
373
                array_set($input, "{$this->column}.$index.$newKey", $value);
374
                /*
375
                 * forget the old key and value
376
                 */
377
                array_forget($input, "{$this->column}.$index.$name");
378
            }
379
        }
380
    }
381
382
    /**
383
     * Prepare input data for insert or update.
384
     *
385
     * @param array $input
386
     *
387
     * @return array
388
     */
389
    public function prepare($input)
390
    {
391
        $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...
392
393
        return $form->setOriginal($this->original, $this->getKeyName())->prepare($input);
394
    }
395
396
    /**
397
     * Build a Nested form.
398
     *
399
     * @param string   $column
400
     * @param \Closure $builder
401
     * @param null     $key
402
     *
403
     * @return NestedForm
404
     */
405
    protected function buildNestedForm($column, \Closure $builder, $key = null)
406
    {
407
        $form = new Form\NestedForm($column, $key);
408
409
        $form->setForm($this->form);
410
411
        call_user_func($builder, $form);
412
413
        $form->hidden($this->getKeyName());
414
415
        $form->hidden(NestedForm::REMOVE_FLAG_NAME)->default(0)->addElementClass(NestedForm::REMOVE_FLAG_CLASS);
416
417
        return $form;
418
    }
419
420
    /**
421
     * Get the HasMany relation key name.
422
     *
423
     * @return string
424
     */
425
    protected function getKeyName()
426
    {
427
        if (is_null($this->form)) {
428
            return;
429
        }
430
431
        return $this->form->model()->{$this->relationName}()->getRelated()->getKeyName();
432
    }
433
434
    /**
435
     * Set view mode.
436
     *
437
     * @param string $mode currently support `tab` mode.
438
     *
439
     * @return $this
440
     *
441
     * @author Edwin Hui
442
     */
443
    public function mode($mode)
444
    {
445
        $this->viewMode = $mode;
446
447
        return $this;
448
    }
449
450
    /**
451
     * Use tab mode to showing hasmany field.
452
     *
453
     * @return HasMany
454
     */
455
    public function useTab()
456
    {
457
        return $this->mode('tab');
458
    }
459
460
    /**
461
     * Build Nested form for related data.
462
     *
463
     * @throws \Exception
464
     *
465
     * @return array
466
     */
467
    protected function buildRelatedForms()
468
    {
469
        if (is_null($this->form)) {
470
            return [];
471
        }
472
473
        $model = $this->form->model();
474
475
        $relation = call_user_func([$model, $this->relationName]);
476
477
        if (!$relation instanceof Relation && !$relation instanceof MorphMany) {
478
            throw new \Exception('hasMany field must be a HasMany or MorphMany relation.');
479
        }
480
481
        $forms = [];
482
483
        /*
484
         * If redirect from `exception` or `validation error` page.
485
         *
486
         * Then get form data from session flash.
487
         *
488
         * Else get data from database.
489
         */
490
        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...
491
            foreach ($values as $key => $data) {
492
                if ($data[NestedForm::REMOVE_FLAG_NAME] == 1) {
493
                    continue;
494
                }
495
496
                $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...
497
                    ->fill($data);
498
            }
499
        } else {
500
            foreach ($this->value as $data) {
501
                $key = array_get($data, $relation->getRelated()->getKeyName());
502
503
                $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...
504
                    ->fill($data);
505
            }
506
        }
507
508
        return $forms;
509
    }
510
511
    /**
512
     * Setup script for this field in different view mode.
513
     *
514
     * @param string $script
515
     *
516
     * @return void
517
     */
518
    protected function setupScript($script)
519
    {
520
        $method = 'setupScriptFor'.ucfirst($this->viewMode).'View';
521
522
        call_user_func([$this, $method], $script);
523
    }
524
525
    /**
526
     * Setup default template script.
527
     *
528
     * @param string $templateScript
529
     *
530
     * @return void
531
     */
532 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...
533
    {
534
        $removeClass = NestedForm::REMOVE_FLAG_CLASS;
535
        $defaultKey = NestedForm::DEFAULT_KEY_NAME;
536
537
        /**
538
         * When add a new sub form, replace all element key in new sub form.
539
         *
540
         * @example comments[new___key__][title]  => comments[new_{index}][title]
541
         *
542
         * {count} is increment number of current sub form count.
543
         */
544
        $script = <<<EOT
545
var index = 0;
546
$('#has-many-{$this->column}').on('click', '.add', function () {
547
548
    var tpl = $('template.{$this->column}-tpl');
549
550
    index++;
551
552
    var template = tpl.html().replace(/{$defaultKey}/g, index);
553
    $('.has-many-{$this->column}-forms').append(template);
554
    {$templateScript}
555
});
556
557
$('#has-many-{$this->column}').on('click', '.remove', function () {
558
    $(this).closest('.has-many-{$this->column}-form').hide();
559
    $(this).closest('.has-many-{$this->column}-form').find('.$removeClass').val(1);
560
});
561
562
EOT;
563
564
        Admin::script($script);
565
    }
566
567
    /**
568
     * Setup tab template script.
569
     *
570
     * @param string $templateScript
571
     *
572
     * @return void
573
     */
574 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...
575
    {
576
        $removeClass = NestedForm::REMOVE_FLAG_CLASS;
577
        $defaultKey = NestedForm::DEFAULT_KEY_NAME;
578
579
        $script = <<<EOT
580
581
$('#has-many-{$this->column} > .nav').off('click', 'i.close-tab').on('click', 'i.close-tab', function(){
582
    var \$navTab = $(this).siblings('a');
583
    var \$pane = $(\$navTab.attr('href'));
584
    if( \$pane.hasClass('new') ){
585
        \$pane.remove();
586
    }else{
587
        \$pane.removeClass('active').find('.$removeClass').val(1);
588
    }
589
    if(\$navTab.closest('li').hasClass('active')){
590
        \$navTab.closest('li').remove();
591
        $('#has-many-{$this->column} > .nav > li:nth-child(1) > a').tab('show');
592
    }else{
593
        \$navTab.closest('li').remove();
594
    }
595
});
596
597
var index = 0;
598
$('#has-many-{$this->column} > .header').off('click', '.add').on('click', '.add', function(){
599
    index++;
600
    var navTabHtml = $('#has-many-{$this->column} > template.nav-tab-tpl').html().replace(/{$defaultKey}/g, index);
601
    var paneHtml = $('#has-many-{$this->column} > template.pane-tpl').html().replace(/{$defaultKey}/g, index);
602
    $('#has-many-{$this->column} > .nav').append(navTabHtml);
603
    $('#has-many-{$this->column} > .tab-content').append(paneHtml);
604
    $('#has-many-{$this->column} > .nav > li:last-child a').tab('show');
605
    {$templateScript}
606
});
607
608
if ($('.has-error').length) {
609
    $('.has-error').parent('.tab-pane').each(function () {
610
        var tabId = '#'+$(this).attr('id');
611
        $('li a[href="'+tabId+'"] i').removeClass('hide');
612
    });
613
    
614
    var first = $('.has-error:first').parent().attr('id');
615
    $('li a[href="#'+first+'"]').tab('show');
616
}
617
EOT;
618
619
        Admin::script($script);
620
    }
621
622
    /**
623
     * Disable create button.
624
     *
625
     * @return $this
626
     */
627
    public function disableCreate()
628
    {
629
        $this->options['allowCreate'] = false;
630
631
        return $this;
632
    }
633
634
    /**
635
     * Disable delete button.
636
     *
637
     * @return $this
638
     */
639
    public function disableDelete()
640
    {
641
        $this->options['allowDelete'] = false;
642
643
        return $this;
644
    }
645
646
    /**
647
     * Render the `HasMany` field.
648
     *
649
     * @throws \Exception
650
     *
651
     * @return \Illuminate\View\View
652
     */
653
    public function render()
654
    {
655
        // specify a view to render.
656
        $this->view = $this->views[$this->viewMode];
657
658
        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...
659
            ->getTemplateHtmlAndScript();
660
661
        $this->setupScript($script);
662
663
        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...
664
            'forms'         => $this->buildRelatedForms(),
665
            'template'      => $template,
666
            'relationName'  => $this->relationName,
667
            'options'       => $this->options,
668
        ]);
669
    }
670
}
671