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

HasMany::buildNestedForm()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 3
dl 0
loc 14
rs 9.7998
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
            return $a;
118
        };
119
120 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...
121
            if (count($a))
122
                foreach ($a as $key => $val) {
123
                array_set($a, str_replace(':', '', $key), $val);
124
                if (preg_match('/[\.\:]/', $key)) {
125
                    unset($a[$key]);
126
                }
127
            }
128
            return $a;
129
        };
130
131
        $input = array_only($input, $this->column);
132
        $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...
133
        $rel = $this->relationName;
134
        $rules = $attributes = [];
135
        $messages = [];
136
        // remove all inputs & keys marked as removed
137
        $availInput = array_filter(array_map(function ($v) {
138
            return $v[NestedForm::REMOVE_FLAG_NAME] ? null : $v;
139
        }, $input[$rel]));
140
        $keys = array_keys($availInput);
141
        /* @var Field $field */
142
        foreach ($form->fields() as $field) {
143
            if (!$fieldRules = $field->getRules()) {
144
                continue;
145
            }
146
            $column = $field->column();
147
            $columns = is_array($column) ? $column : [$column];
148
            if ($field instanceof Field\MultipleSelect) {
149
                foreach ($keys as $key) {
150
                    $availInput[$key][$column] = array_filter($availInput[$key][$column], 'strlen');
151
                    $availInput[$key][$column] = $availInput[$key][$column] ? : null;
152
                }
153
            }
154
            // if($field instanceof Field\File)
155
            // {
156
            //     dd(request());
157
            // }
158
            $newColumn = call_user_func_array('array_merge', array_map(function ($u) use ($columns, $rel) {
159
                return array_map(function ($k, $v) use ($u, $rel) {
160
                            //Fix ResetInput Function! A Headache Implementation!
161
                    return !$k ? "{$rel}.{$u}.{$v}" : "{$rel}.{$u}.{$v}:{$k}";
162
                }, array_keys($columns), array_values($columns));
163
            }, $keys));
164
165
            $fieldRules = is_array($fieldRules) ? implode('|', $fieldRules) : $fieldRules;
166
            $rules = array_merge($rules, call_user_func_array(
167
                'array_merge',
168
                array_map(function ($v) use ($fieldRules) {
169
                    return [$v => $fieldRules];
170
                }, $newColumn)
171
            ));
172
            $attributes = array_merge($attributes, call_user_func_array(
173
                'array_merge',
174 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...
175
                    //Fix ResetInput Function! A Headache Implementation!
176
                    $u = $field->label();
177
                    $u .= is_array($field->column()) ? '[' . explode(':', explode('.', $v)[1])[0] . ']' : '';
178
                    return [$v => "{$u}"];
179
                }, $newColumn)
180
            ));
181 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...
182
183
                $newMessages = array_map(function ($v) use ($field, $availInput, $array_key_attach_str) {
184
                    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...
185
                    //Fix ResetInput Function! A Headache Implementation!
186
                    $col1 = explode(':', $c)[0];
187
                    if (!array_key_exists($col1, $availInput[$k])) return [null => null];
188
                    $rows = $availInput[$k][$col1];
189
                    if (!is_array($rows))
190
                        return $array_key_attach_str($field->validationMessages, $v);
191
                    $r = [];
192
                    foreach (array_keys($rows) as $k) {
193
                        $k = "{$v}{$k}";
194
                        $r = array_merge($r, $array_key_attach_str($field->validationMessages, $k));
195
                    }
196
                    return $r;
197
                }, $newColumn);
198
                $newMessages = call_user_func_array('array_merge', $newMessages);
199
                $messages = array_merge($messages, $newMessages);
200
            }
201
        }
202
203
        if (empty($rules)) {
204
            return false;
205
        }
206
207
        $newInput = call_user_func_array('array_merge', array_map(function ($u) use ($availInput) {
208
            list($rel, $key, $col) = explode('.', $u);
209
            $idx = "{$rel}.{$key}.{$col}";
210
            //Fix ResetInput Function! A Headache Implementation!
211
            $col1 = explode(':', $col)[0];
212
            if (!array_key_exists($col1, $availInput[$key])) return [null => null];
213
            if (is_array($availInput[$key][$col1])) {
214
                return call_user_func_array('array_merge', array_map(function ($x, $y) use ($idx) {
215
                    return ["{$idx}{$x}" => $y];
216
                }, array_keys($availInput[$key][$col1]), $availInput[$key][$col1]));
217
            }
218
            return ["{$idx}" => $availInput[$key][$col1]];
219
        }, array_keys($rules)));
220
        $newInput = $array_key_clean_undot($newInput);
221
222
        $newRules = array_map(function ($u) use ($availInput, $rules) {
223
            list($rel, $key, $col) = explode('.', $u);
224
            $idx = "{$rel}.{$key}.{$col}";
225
            //Fix ResetInput Function! A Headache Implementation!
226
            $col1 = explode(':', $col)[0];
227
            if (!array_key_exists($col1, $availInput[$key])) return [null => null];
228
            if (is_array($availInput[$key][$col1])) {
229
                return call_user_func_array('array_merge', array_map(function ($x) use ($idx, $rules) {
230
                    return ["{$idx}{$x}" => $rules[$idx]];
231
                }, array_keys($availInput[$key][$col1])));
232
            }
233
            return ["{$idx}" => $rules[$idx]];
234
235
        }, array_keys($rules));
236
        $newRules = array_filter(call_user_func_array('array_merge', $newRules), 'strlen', ARRAY_FILTER_USE_KEY);
237
        $newRules = $array_key_clean($newRules);;
238
239
        $newAttributes = array_map(function ($u) use ($availInput, $attributes) {
240
            list($rel, $key, $col) = explode('.', $u);
241
            $idx = "{$rel}.{$key}.{$col}";
242
            //Fix ResetInput Function! A Headache Implementation!
243
            $col1 = explode(':', $col)[0];
244
            if (!array_key_exists($col1, $availInput[$key])) return [null => null];
245 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...
246
                if (array_keys($availInput[$key][$col1]))
247
                    return call_user_func_array('array_merge', array_map(function ($x) use ($idx, $attributes) {
248
                    return ["{$idx}.{$x}" => $attributes[$idx]];
249
                }, array_keys($availInput[$key][$col1])));
250
                return [null => null];
251
            }
252
253
            return ["{$idx}" => $attributes[$idx]];
254
        }, array_keys($attributes));
255
        $newAttributes = array_filter(call_user_func_array('array_merge', $newAttributes), 'strlen');
256
        $newAttributes = $array_key_clean($newAttributes);
257
258
        $messages = $array_key_clean($messages);
259
260
        if (empty($newInput)) {
261
            $newInput = [$rel => $availInput];
262
        }
263
        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...
264
    }
265
266
    /**
267
     * Format validation attributes.
268
     *
269
     * @param array  $input
270
     * @param string $label
271
     * @param string $column
272
     *
273
     * @return array
274
     */
275 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...
276
    {
277
        $new = $attributes = [];
278
279
        if (is_array($column)) {
280
            foreach ($column as $index => $col) {
281
                $new[$col . $index] = $col;
282
            }
283
        }
284
285
        foreach (array_keys(array_dot($input)) as $key) {
286
            if (is_string($column)) {
287
                if (Str::endsWith($key, ".$column")) {
288
                    $attributes[$key] = $label;
289
                }
290
            } else {
291
                foreach ($new as $k => $val) {
292
                    if (Str::endsWith($key, ".$k")) {
293
                        $attributes[$key] = $label . "[$val]";
294
                    }
295
                }
296
            }
297
        }
298
299
        return $attributes;
300
    }
301
302
    /**
303
     * Reset input key for validation.
304
     *
305
     * @param array $input
306
     * @param array $column $column is the column name array set
307
     *
308
     * @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...
309
     */
310
    protected function resetInputKey(array &$input, array $column)
311
    {
312
        /**
313
         * flip the column name array set.
314
         *
315
         * for example, for the DateRange, the column like as below
316
         *
317
         * ["start" => "created_at", "end" => "updated_at"]
318
         *
319
         * to:
320
         *
321
         * [ "created_at" => "start", "updated_at" => "end" ]
322
         */
323
        $column = array_flip($column);
324
325
        /**
326
         * $this->column is the inputs array's node name, default is the relation name.
327
         *
328
         * So... $input[$this->column] is the data of this column's inputs data
329
         *
330
         * in the HasMany relation, has many data/field set, $set is field set in the below
331
         */
332
        foreach ($input[$this->column] as $index => $set) {
333
334
            /*
335
             * foreach the field set to find the corresponding $column
336
             */
337 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...
338
                /*
339
                 * if doesn't have column name, continue to the next loop
340
                 */
341
                if (!array_key_exists($name, $column)) {
342
                    continue;
343
                }
344
345
                /**
346
                 * example:  $newKey = created_atstart.
347
                 *
348
                 * Σ( ° △ °|||)︴
349
                 *
350
                 * I don't know why a form need range input? Only can imagine is for range search....
351
                 */
352
                $newKey = $name . $column[$name];
353
354
                /*
355
                 * set new key
356
                 */
357
                array_set($input, "{$this->column}.$index.$newKey", $value);
358
                /*
359
                 * forget the old key and value
360
                 */
361
                array_forget($input, "{$this->column}.$index.$name");
362
            }
363
        }
364
    }
365
366
    /**
367
     * Prepare input data for insert or update.
368
     *
369
     * @param array $input
370
     *
371
     * @return array
372
     */
373
    public function prepare($input)
374
    {
375
        $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...
376
377
        return $form->setOriginal($this->original, $this->getKeyName())->prepare($input);
378
    }
379
380
    /**
381
     * Build a Nested form.
382
     *
383
     * @param string   $column
384
     * @param \Closure $builder
385
     * @param null     $key
386
     *
387
     * @return NestedForm
388
     */
389
    protected function buildNestedForm($column, \Closure $builder, $key = null)
390
    {
391
        $form = new Form\NestedForm($column, $key);
392
393
        $form->setForm($this->form);
394
395
        call_user_func($builder, $form);
396
397
        $form->hidden($this->getKeyName());
398
399
        $form->hidden(NestedForm::REMOVE_FLAG_NAME)->default(0)->addElementClass(NestedForm::REMOVE_FLAG_CLASS);
400
401
        return $form;
402
    }
403
404
    /**
405
     * Get the HasMany relation key name.
406
     *
407
     * @return string
408
     */
409
    protected function getKeyName()
410
    {
411
        if (is_null($this->form)) {
412
            return;
413
        }
414
415
        return $this->form->model()->{$this->relationName}()->getRelated()->getKeyName();
416
    }
417
418
    /**
419
     * Set view mode.
420
     *
421
     * @param string $mode currently support `tab` mode.
422
     *
423
     * @return $this
424
     *
425
     * @author Edwin Hui
426
     */
427
    public function mode($mode)
428
    {
429
        $this->viewMode = $mode;
430
431
        return $this;
432
    }
433
434
    /**
435
     * Use tab mode to showing hasmany field.
436
     *
437
     * @return HasMany
438
     */
439
    public function useTab()
440
    {
441
        return $this->mode('tab');
442
    }
443
444
    /**
445
     * Build Nested form for related data.
446
     *
447
     * @throws \Exception
448
     *
449
     * @return array
450
     */
451
    protected function buildRelatedForms()
452
    {
453
        if (is_null($this->form)) {
454
            return [];
455
        }
456
457
        $model = $this->form->model();
458
459
        $relation = call_user_func([$model, $this->relationName]);
460
461
        if (!$relation instanceof Relation && !$relation instanceof MorphMany) {
462
            throw new \Exception('hasMany field must be a HasMany or MorphMany relation.');
463
        }
464
465
        $forms = [];
466
467
        /*
468
         * If redirect from `exception` or `validation error` page.
469
         *
470
         * Then get form data from session flash.
471
         *
472
         * Else get data from database.
473
         */
474
        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...
475
            foreach ($values as $key => $data) {
476
                if ($data[NestedForm::REMOVE_FLAG_NAME] == 1) {
477
                    continue;
478
                }
479
480
                $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...
481
                    ->fill($data);
482
            }
483
        } else {
484
            foreach ($this->value as $data) {
485
                $key = array_get($data, $relation->getRelated()->getKeyName());
486
487
                $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...
488
                    ->fill($data);
489
            }
490
        }
491
492
        return $forms;
493
    }
494
495
    /**
496
     * Setup script for this field in different view mode.
497
     *
498
     * @param string $script
499
     *
500
     * @return void
501
     */
502
    protected function setupScript($script)
503
    {
504
        $method = 'setupScriptFor' . ucfirst($this->viewMode) . 'View';
505
506
        call_user_func([$this, $method], $script);
507
    }
508
509
    /**
510
     * Setup default template script.
511
     *
512
     * @param string $templateScript
513
     *
514
     * @return void
515
     */
516 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...
517
    {
518
        $removeClass = NestedForm::REMOVE_FLAG_CLASS;
519
        $defaultKey = NestedForm::DEFAULT_KEY_NAME;
520
521
        /**
522
         * When add a new sub form, replace all element key in new sub form.
523
         *
524
         * @example comments[new___key__][title]  => comments[new_{index}][title]
525
         *
526
         * {count} is increment number of current sub form count.
527
         */
528
        $script = <<<EOT
529
var index = 0;
530
$('#has-many-{$this->column}').on('click', '.add', function () {
531
532
    var tpl = $('template.{$this->column}-tpl');
533
534
    index++;
535
536
    var template = tpl.html().replace(/{$defaultKey}/g, index);
537
    $('.has-many-{$this->column}-forms').append(template);
538
    {$templateScript}
539
});
540
541
$('#has-many-{$this->column}').on('click', '.remove', function () {
542
    $(this).closest('.has-many-{$this->column}-form').hide();
543
    $(this).closest('.has-many-{$this->column}-form').find('.$removeClass').val(1);
544
});
545
546
EOT;
547
548
        Admin::script($script);
549
    }
550
551
    /**
552
     * Setup tab template script.
553
     *
554
     * @param string $templateScript
555
     *
556
     * @return void
557
     */
558 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...
559
    {
560
        $removeClass = NestedForm::REMOVE_FLAG_CLASS;
561
        $defaultKey = NestedForm::DEFAULT_KEY_NAME;
562
563
        $script = <<<EOT
564
565
$('#has-many-{$this->column} > .nav').off('click', 'i.close-tab').on('click', 'i.close-tab', function(){
566
    var \$navTab = $(this).siblings('a');
567
    var \$pane = $(\$navTab.attr('href'));
568
    if( \$pane.hasClass('new') ){
569
        \$pane.remove();
570
    }else{
571
        \$pane.removeClass('active').find('.$removeClass').val(1);
572
    }
573
    if(\$navTab.closest('li').hasClass('active')){
574
        \$navTab.closest('li').remove();
575
        $('#has-many-{$this->column} > .nav > li:nth-child(1) > a').tab('show');
576
    }else{
577
        \$navTab.closest('li').remove();
578
    }
579
});
580
581
var index = 0;
582
$('#has-many-{$this->column} > .header').off('click', '.add').on('click', '.add', function(){
583
    index++;
584
    var navTabHtml = $('#has-many-{$this->column} > template.nav-tab-tpl').html().replace(/{$defaultKey}/g, index);
585
    var paneHtml = $('#has-many-{$this->column} > template.pane-tpl').html().replace(/{$defaultKey}/g, index);
586
    $('#has-many-{$this->column} > .nav').append(navTabHtml);
587
    $('#has-many-{$this->column} > .tab-content').append(paneHtml);
588
    $('#has-many-{$this->column} > .nav > li:last-child a').tab('show');
589
    {$templateScript}
590
});
591
592
if ($('.has-error').length) {
593
    $('.has-error').parent('.tab-pane').each(function () {
594
        var tabId = '#'+$(this).attr('id');
595
        $('li a[href="'+tabId+'"] i').removeClass('hide');
596
    });
597
    
598
    var first = $('.has-error:first').parent().attr('id');
599
    $('li a[href="#'+first+'"]').tab('show');
600
}
601
EOT;
602
603
        Admin::script($script);
604
    }
605
606
    /**
607
     * Disable create button.
608
     *
609
     * @return $this
610
     */
611
    public function disableCreate()
612
    {
613
        $this->options['allowCreate'] = false;
614
615
        return $this;
616
    }
617
618
    /**
619
     * Disable delete button.
620
     *
621
     * @return $this
622
     */
623
    public function disableDelete()
624
    {
625
        $this->options['allowDelete'] = false;
626
627
        return $this;
628
    }
629
630
    /**
631
     * Render the `HasMany` field.
632
     *
633
     * @throws \Exception
634
     *
635
     * @return \Illuminate\View\View
636
     */
637
    public function render()
638
    {
639
        // specify a view to render.
640
        $this->view = $this->views[$this->viewMode];
641
642
        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...
643
            ->getTemplateHtmlAndScript();
644
645
        $this->setupScript($script);
646
647
        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...
648
            'forms' => $this->buildRelatedForms(),
649
            'template' => $template,
650
            'relationName' => $this->relationName,
651
            'options' => $this->options,
652
        ]);
653
    }
654
}
655