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

HasMany::render()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 17
rs 9.7
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
13
/**
14
 * Class HasMany.
15
 */
16
class HasMany extends Field
17
{
18
    /**
19
     * Relation name.
20
     *
21
     * @var string
22
     */
23
    protected $relationName = '';
24
25
    /**
26
     * Form builder.
27
     *
28
     * @var \Closure
29
     */
30
    protected $builder = null;
31
32
    /**
33
     * Form data.
34
     *
35
     * @var array
36
     */
37
    protected $value = [];
38
39
    /**
40
     * View Mode.
41
     *
42
     * Supports `default` and `tab` currently.
43
     *
44
     * @var string
45
     */
46
    protected $viewMode = 'default';
47
48
    /**
49
     * Available views for HasMany field.
50
     *
51
     * @var array
52
     */
53
    protected $views = [
54
        'default' => 'admin::form.hasmany',
55
        'tab'     => 'admin::form.hasmanytab',
56
    ];
57
58
    /**
59
     * Options for template.
60
     *
61
     * @var array
62
     */
63
    protected $options = [
64
        'allowCreate' => true,
65
        'allowDelete' => true,
66
    ];
67
68
    /**
69
     * Create a new HasMany field instance.
70
     *
71
     * @param $relationName
72
     * @param array $arguments
73
     */
74 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...
75
    {
76
        $this->relationName = $relationName;
77
78
        $this->column = $relationName;
79
80
        if (count($arguments) == 1) {
81
            $this->label = $this->formatLabel();
82
            $this->builder = $arguments[0];
83
        }
84
85
        if (count($arguments) == 2) {
86
            list($this->label, $this->builder) = $arguments;
87
        }
88
    }
89
90
    /**
91
     * Get validator for this field.
92
     *
93
     * @param array $input
94
     *
95
     * @return bool|Validator
96
     */
97
    public function getValidator(array $input)
98
    {
99
        if (!array_key_exists($this->column, $input)) {
100
            return false;
101
        }
102
103 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...
104
            return call_user_func_array(
105
                'array_merge',
106
                array_map(function ($u, $v) use ($b, $c) {
107
                    return ["{$b}{$c}{$u}" => $v];
108
                }, array_keys($a), array_values($a))
109
            );
110
        };
111
112 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...
113
            $a = count($a) ? call_user_func_array('array_merge', array_map(function ($k, $v) {
114
                return [str_replace(':', '', $k) => $v];
115
            }, array_keys($a), array_values($a))) : $a;
116
117
            return $a;
118
        };
119
120
        $array_clean_merge = function (array $a, $b) {
121
            return array_merge($a, call_user_func_array('array_merge', $b));
122
        };
123
124 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...
125
            $keys = preg_grep('/[\.\:]/', array_keys($a));
126
            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...
127
                foreach ($keys as $key) {
128
                    array_set($a, str_replace(':', '', $key), $a[$key]);
129
                    unset($a[$key]);
130
                }
131
            }
132
133
            return $a;
134
        };
135
136
        $input = array_only($input, $this->column);
137
        $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...
138
        $rel = $this->relationName;
139
        $rules = $attributes = $messages = $newInputs = [];
140
        // remove all inputs & keys marked as removed
141
        $availInput = array_filter(array_map(function ($v) {
142
            return $v[NestedForm::REMOVE_FLAG_NAME] ? null : $v;
143
        }, $input[$rel]));
144
        $keys = array_keys($availInput);
145
        /* @var Field $field */
146
        foreach ($form->fields() as $field) {
147
            if (!$fieldRules = $field->getRules()) {
148
                continue;
149
            }
150
            $column = $field->column();
151
            $columns = is_array($column) ? $column : [$column];
152 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...
153
                foreach ($keys as $key) {
154
                    $availInput[$key][$column] = array_filter($availInput[$key][$column], 'strlen') ?: null;
155
                }
156
            }
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}:{$k}" : "{$rel}.{$u}.{$v}";
162
                }, array_keys($columns), array_values($columns));
163
            }, $keys));
164
165
            $fieldRules = is_array($fieldRules) ? implode('|', $fieldRules) : $fieldRules;
166 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...
167
                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...
168
                //Fix ResetInput Function! A Headache Implementation!
169
                $col = explode(':', $c)[0];
170
                if (array_key_exists($col, $availInput[$k]) && is_array($availInput[$k][$col])) {
171
                    return $array_key_attach_str(preg_replace('/./', $fieldRules, $availInput[$k][$col]), $v, ':');
172
                }
173
174
                //May Have Problem in Dealing with File Upload in Edit Mode
175
                return [$v => $fieldRules];
176
            }, $newColumn);
177
            $rules = $array_clean_merge($rules, $newRules);
178
179 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...
180
                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...
181
                //Fix ResetInput Function! A Headache Implementation!
182
                $col = explode(':', $c)[0];
183
                if (!array_key_exists($col, $availInput[$k])) {
184
                    //May Have Problem in Dealing with File Upload in Edit Mode
185
                    return [$v => null];
186
                }
187
188
                if (is_array($availInput[$k][$col])) {
189
                    return $array_key_attach_str($availInput[$k][$col], $v, ':');
190
                }
191
192
                return [$v => $availInput[$k][$col]];
193
            }, $newColumn);
194
            $newInputs = $array_clean_merge($newInputs, $newInput);
195
196 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...
197
                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...
198
                //Fix ResetInput Function! A Headache Implementation!
199
                $col = explode(':', $c)[0];
200
                if (array_key_exists($col, $availInput[$k]) && is_array($availInput[$k][$col])) {
201
                    return call_user_func_array('array_merge', array_map(function ($u) use ($v, $field) {
202
                        $w = $field->label();
203
                        //Fix ResetInput Function! A Headache Implementation!
204
                        $w .= is_array($field->column()) ? '['.explode(':', explode('.', $v)[2])[0].']' : '';
205
206
                        return ["{$v}:{$u}" => $w];
207
                    }, array_keys($availInput[$k][$col])));
208
                }
209
210
                //May Have Problem in Dealing with File Upload in Edit Mode
211
                $w = $field->label();
212
                //Fix ResetInput Function! A Headache Implementation!
213
                $w .= is_array($field->column()) ? '['.explode(':', explode('.', $v)[2])[0].']' : '';
214
215
                return [$v => $w];
216
            }, $newColumn);
217
            $attributes = $array_clean_merge($attributes, $newAttributes);
218
219 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...
220
                $newMessages = array_map(function ($v) use ($field, $availInput, $array_key_attach_str) {
221
                    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...
222
                    //Fix ResetInput Function! A Headache Implementation!
223
                    $col = explode(':', $c)[0];
224
                    if (array_key_exists($col, $availInput[$k]) && is_array($availInput[$k][$col])) {
225
                        return call_user_func_array('array_merge', array_map(function ($u) use ($v, $field, $array_key_attach_str) {
226
                            return $array_key_attach_str($field->validationMessages, "{$v}:{$u}");
227
                        }, array_keys($availInput[$k][$col])));
228
                    }
229
230
                    //May Have Problem in Dealing with File Upload in Edit Mode
231
                    return $array_key_attach_str($field->validationMessages, $v);
232
                }, $newColumn);
233
                $messages = $array_clean_merge($messages, $newMessages);
234
            }
235
        }
236
237
        $rules = array_filter($rules, 'strlen');
238
        if (empty($rules)) {
239
            return false;
240
        }
241
242
        $attributes = array_filter($attributes, 'strlen');
243
        $messages = array_filter($messages, 'strlen');
244
        $input = $array_key_clean_undot(array_filter($newInputs, 'strlen', ARRAY_FILTER_USE_KEY));
245
        $rules = $array_key_clean($rules);
246
        $attributes = $array_key_clean($attributes);
247
        $messages = $array_key_clean($messages);
248
249
        if (empty($input)) {
250
            $input = [$rel => $availInput];
251
        }
252
253
        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...
254
    }
255
256
    /**
257
     * Prepare input data for insert or update.
258
     *
259
     * @param array $input
260
     *
261
     * @return array
262
     */
263
    public function prepare($input)
264
    {
265
        $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...
266
267
        return $form->setOriginal($this->original, $this->getKeyName())->prepare($input);
268
    }
269
270
    /**
271
     * Build a Nested form.
272
     *
273
     * @param string   $column
274
     * @param \Closure $builder
275
     * @param null     $key
276
     *
277
     * @return NestedForm
278
     */
279
    protected function buildNestedForm($column, \Closure $builder, $key = null)
280
    {
281
        $form = new Form\NestedForm($column, $key);
282
283
        $form->setForm($this->form);
284
285
        call_user_func($builder, $form);
286
287
        $form->hidden($this->getKeyName());
288
289
        $form->hidden(NestedForm::REMOVE_FLAG_NAME)->default(0)->addElementClass(NestedForm::REMOVE_FLAG_CLASS);
290
291
        return $form;
292
    }
293
294
    /**
295
     * Get the HasMany relation key name.
296
     *
297
     * @return string
298
     */
299
    protected function getKeyName()
300
    {
301
        if (is_null($this->form)) {
302
            return;
303
        }
304
305
        return $this->form->model()->{$this->relationName}()->getRelated()->getKeyName();
306
    }
307
308
    /**
309
     * Set view mode.
310
     *
311
     * @param string $mode currently support `tab` mode.
312
     *
313
     * @return $this
314
     *
315
     * @author Edwin Hui
316
     */
317
    public function mode($mode)
318
    {
319
        $this->viewMode = $mode;
320
321
        return $this;
322
    }
323
324
    /**
325
     * Use tab mode to showing hasmany field.
326
     *
327
     * @return HasMany
328
     */
329
    public function useTab()
330
    {
331
        return $this->mode('tab');
332
    }
333
334
    /**
335
     * Build Nested form for related data.
336
     *
337
     * @throws \Exception
338
     *
339
     * @return array
340
     */
341
    protected function buildRelatedForms()
342
    {
343
        if (is_null($this->form)) {
344
            return [];
345
        }
346
347
        $model = $this->form->model();
348
349
        $relation = call_user_func([$model, $this->relationName]);
350
351
        if (!$relation instanceof Relation && !$relation instanceof MorphMany) {
352
            throw new \Exception('hasMany field must be a HasMany or MorphMany relation.');
353
        }
354
355
        $forms = [];
356
357
        /*
358
         * If redirect from `exception` or `validation error` page.
359
         *
360
         * Then get form data from session flash.
361
         *
362
         * Else get data from database.
363
         */
364
        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...
365
            foreach ($values as $key => $data) {
366
                if ($data[NestedForm::REMOVE_FLAG_NAME] == 1) {
367
                    continue;
368
                }
369
370
                $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...
371
                    ->fill($data);
372
            }
373
        } else {
374
            foreach ($this->value as $data) {
375
                $key = array_get($data, $relation->getRelated()->getKeyName());
376
377
                $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...
378
                    ->fill($data);
379
            }
380
        }
381
382
        return $forms;
383
    }
384
385
    /**
386
     * Setup script for this field in different view mode.
387
     *
388
     * @param string $script
389
     *
390
     * @return void
391
     */
392
    protected function setupScript($script)
393
    {
394
        $method = 'setupScriptFor'.ucfirst($this->viewMode).'View';
395
396
        call_user_func([$this, $method], $script);
397
    }
398
399
    /**
400
     * Setup default template script.
401
     *
402
     * @param string $templateScript
403
     *
404
     * @return void
405
     */
406 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...
407
    {
408
        $removeClass = NestedForm::REMOVE_FLAG_CLASS;
409
        $defaultKey = NestedForm::DEFAULT_KEY_NAME;
410
411
        /**
412
         * When add a new sub form, replace all element key in new sub form.
413
         *
414
         * @example comments[new___key__][title]  => comments[new_{index}][title]
415
         *
416
         * {count} is increment number of current sub form count.
417
         */
418
        $script = <<<EOT
419
var index = 0;
420
$('#has-many-{$this->column}').on('click', '.add', function() {
421
422
    var tpl = $('template.{$this->column}-tpl');
423
424
    index++;
425
426
    var template = tpl.html().replace(/{$defaultKey}/g, index);
427
    $('.has-many-{$this->column}-forms').append(template);
428
    {$templateScript}
429
});
430
431
$('#has-many-{$this->column}').on('click', '.remove', function() {
432
    $(this).closest('.has-many-{$this->column}-form').hide();
433
    $(this).closest('.has-many-{$this->column}-form').find('.$removeClass').val(1);
434
});
435
436
EOT;
437
438
        Admin::script($script);
439
    }
440
441
    /**
442
     * Setup tab template script.
443
     *
444
     * @param string $templateScript
445
     *
446
     * @return void
447
     */
448 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...
449
    {
450
        $removeClass = NestedForm::REMOVE_FLAG_CLASS;
451
        $defaultKey = NestedForm::DEFAULT_KEY_NAME;
452
453
        $script = <<<EOT
454
455
$('#has-many-{$this->column} > .nav').off('click', 'i.close-tab').on('click', 'i.close-tab', function(){
456
    var \$navTab = $(this).siblings('a');
457
    var \$pane = $(\$navTab.attr('href'));
458
    if( \$pane.hasClass('new') ){
459
        \$pane.remove();
460
    }else{
461
        \$pane.removeClass('active').find('.$removeClass').val(1);
462
    }
463
    if(\$navTab.closest('li').hasClass('active')){
464
        \$navTab.closest('li').remove();
465
        $('#has-many-{$this->column} > .nav > li:nth-child(1) > a').tab('show');
466
    }else{
467
        \$navTab.closest('li').remove();
468
    }
469
});
470
471
var index = 0;
472
$('#has-many-{$this->column} > .header').off('click', '.add').on('click', '.add', function(){
473
    index++;
474
    var navTabHtml = $('#has-many-{$this->column} > template.nav-tab-tpl').html().replace(/{$defaultKey}/g, index);
475
    var paneHtml = $('#has-many-{$this->column} > template.pane-tpl').html().replace(/{$defaultKey}/g, index);
476
    $('#has-many-{$this->column} > .nav').append(navTabHtml);
477
    $('#has-many-{$this->column} > .tab-content').append(paneHtml);
478
    $('#has-many-{$this->column} > .nav > li:last-child a').tab('show');
479
    {$templateScript}
480
});
481
482
if ($('.has-error').length) {
483
    $('.has-error').parent('.tab-pane').each(function() {
484
        var tabId = '#'+$(this).attr('id');
485
        $('li a[href="'+tabId+'"] i').removeClass('hide');
486
    });
487
    
488
    var first = $('.has-error:first').parent().attr('id');
489
    $('li a[href="#'+first+'"]').tab('show');
490
}
491
EOT;
492
493
        Admin::script($script);
494
    }
495
496
    /**
497
     * Disable create button.
498
     *
499
     * @return $this
500
     */
501
    public function disableCreate()
502
    {
503
        $this->options['allowCreate'] = false;
504
505
        return $this;
506
    }
507
508
    /**
509
     * Disable delete button.
510
     *
511
     * @return $this
512
     */
513
    public function disableDelete()
514
    {
515
        $this->options['allowDelete'] = false;
516
517
        return $this;
518
    }
519
520
    /**
521
     * Render the `HasMany` field.
522
     *
523
     * @throws \Exception
524
     *
525
     * @return \Illuminate\View\View
526
     */
527
    public function render()
528
    {
529
        // specify a view to render.
530
        $this->view = $this->views[$this->viewMode];
531
532
        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...
533
            ->getTemplateHtmlAndScript();
534
535
        $this->setupScript($script);
536
537
        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...
538
            'forms'        => $this->buildRelatedForms(),
539
            'template'     => $template,
540
            'relationName' => $this->relationName,
541
            'options'      => $this->options,
542
        ]);
543
    }
544
}
545