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

HasMany::mode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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