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

HasMany::setupScript()   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
     * Prepare input data for insert or update.
276
     *
277
     * @param array $input
278
     *
279
     * @return array
280
     */
281
    public function prepare($input)
282
    {
283
        $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...
284
285
        return $form->setOriginal($this->original, $this->getKeyName())->prepare($input);
286
    }
287
288
    /**
289
     * Build a Nested form.
290
     *
291
     * @param string   $column
292
     * @param \Closure $builder
293
     * @param null     $key
294
     *
295
     * @return NestedForm
296
     */
297
    protected function buildNestedForm($column, \Closure $builder, $key = null)
298
    {
299
        $form = new Form\NestedForm($column, $key);
300
301
        $form->setForm($this->form);
302
303
        call_user_func($builder, $form);
304
305
        $form->hidden($this->getKeyName());
306
307
        $form->hidden(NestedForm::REMOVE_FLAG_NAME)->default(0)->addElementClass(NestedForm::REMOVE_FLAG_CLASS);
308
309
        return $form;
310
    }
311
312
    /**
313
     * Get the HasMany relation key name.
314
     *
315
     * @return string
316
     */
317
    protected function getKeyName()
318
    {
319
        if (is_null($this->form)) {
320
            return;
321
        }
322
323
        return $this->form->model()->{$this->relationName}()->getRelated()->getKeyName();
324
    }
325
326
    /**
327
     * Set view mode.
328
     *
329
     * @param string $mode currently support `tab` mode.
330
     *
331
     * @return $this
332
     *
333
     * @author Edwin Hui
334
     */
335
    public function mode($mode)
336
    {
337
        $this->viewMode = $mode;
338
339
        return $this;
340
    }
341
342
    /**
343
     * Use tab mode to showing hasmany field.
344
     *
345
     * @return HasMany
346
     */
347
    public function useTab()
348
    {
349
        return $this->mode('tab');
350
    }
351
352
    /**
353
     * Build Nested form for related data.
354
     *
355
     * @throws \Exception
356
     *
357
     * @return array
358
     */
359
    protected function buildRelatedForms()
360
    {
361
        if (is_null($this->form)) {
362
            return [];
363
        }
364
365
        $model = $this->form->model();
366
367
        $relation = call_user_func([$model, $this->relationName]);
368
369
        if (!$relation instanceof Relation && !$relation instanceof MorphMany) {
370
            throw new \Exception('hasMany field must be a HasMany or MorphMany relation.');
371
        }
372
373
        $forms = [];
374
375
        /*
376
         * If redirect from `exception` or `validation error` page.
377
         *
378
         * Then get form data from session flash.
379
         *
380
         * Else get data from database.
381
         */
382
        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...
383
            foreach ($values as $key => $data) {
384
                if ($data[NestedForm::REMOVE_FLAG_NAME] == 1) {
385
                    continue;
386
                }
387
388
                $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...
389
                    ->fill($data);
390
            }
391
        } else {
392
            foreach ($this->value as $data) {
393
                $key = array_get($data, $relation->getRelated()->getKeyName());
394
395
                $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...
396
                    ->fill($data);
397
            }
398
        }
399
400
        return $forms;
401
    }
402
403
    /**
404
     * Setup script for this field in different view mode.
405
     *
406
     * @param string $script
407
     *
408
     * @return void
409
     */
410
    protected function setupScript($script)
411
    {
412
        $method = 'setupScriptFor' . ucfirst($this->viewMode) . 'View';
413
414
        call_user_func([$this, $method], $script);
415
    }
416
417
    /**
418
     * Setup default template script.
419
     *
420
     * @param string $templateScript
421
     *
422
     * @return void
423
     */
424 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...
425
    {
426
        $removeClass = NestedForm::REMOVE_FLAG_CLASS;
427
        $defaultKey = NestedForm::DEFAULT_KEY_NAME;
428
429
        /**
430
         * When add a new sub form, replace all element key in new sub form.
431
         *
432
         * @example comments[new___key__][title]  => comments[new_{index}][title]
433
         *
434
         * {count} is increment number of current sub form count.
435
         */
436
        $script = <<<EOT
437
var index = 0;
438
$('#has-many-{$this->column}').on('click', '.add', function() {
439
440
    var tpl = $('template.{$this->column}-tpl');
441
442
    index++;
443
444
    var template = tpl.html().replace(/{$defaultKey}/g, index);
445
    $('.has-many-{$this->column}-forms').append(template);
446
    {$templateScript}
447
});
448
449
$('#has-many-{$this->column}').on('click', '.remove', function() {
450
    $(this).closest('.has-many-{$this->column}-form').hide();
451
    $(this).closest('.has-many-{$this->column}-form').find('.$removeClass').val(1);
452
});
453
454
EOT;
455
456
        Admin::script($script);
457
    }
458
459
    /**
460
     * Setup tab template script.
461
     *
462
     * @param string $templateScript
463
     *
464
     * @return void
465
     */
466 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...
467
    {
468
        $removeClass = NestedForm::REMOVE_FLAG_CLASS;
469
        $defaultKey = NestedForm::DEFAULT_KEY_NAME;
470
471
        $script = <<<EOT
472
473
$('#has-many-{$this->column} > .nav').off('click', 'i.close-tab').on('click', 'i.close-tab', function(){
474
    var \$navTab = $(this).siblings('a');
475
    var \$pane = $(\$navTab.attr('href'));
476
    if( \$pane.hasClass('new') ){
477
        \$pane.remove();
478
    }else{
479
        \$pane.removeClass('active').find('.$removeClass').val(1);
480
    }
481
    if(\$navTab.closest('li').hasClass('active')){
482
        \$navTab.closest('li').remove();
483
        $('#has-many-{$this->column} > .nav > li:nth-child(1) > a').tab('show');
484
    }else{
485
        \$navTab.closest('li').remove();
486
    }
487
});
488
489
var index = 0;
490
$('#has-many-{$this->column} > .header').off('click', '.add').on('click', '.add', function(){
491
    index++;
492
    var navTabHtml = $('#has-many-{$this->column} > template.nav-tab-tpl').html().replace(/{$defaultKey}/g, index);
493
    var paneHtml = $('#has-many-{$this->column} > template.pane-tpl').html().replace(/{$defaultKey}/g, index);
494
    $('#has-many-{$this->column} > .nav').append(navTabHtml);
495
    $('#has-many-{$this->column} > .tab-content').append(paneHtml);
496
    $('#has-many-{$this->column} > .nav > li:last-child a').tab('show');
497
    {$templateScript}
498
});
499
500
if ($('.has-error').length) {
501
    $('.has-error').parent('.tab-pane').each(function() {
502
        var tabId = '#'+$(this).attr('id');
503
        $('li a[href="'+tabId+'"] i').removeClass('hide');
504
    });
505
    
506
    var first = $('.has-error:first').parent().attr('id');
507
    $('li a[href="#'+first+'"]').tab('show');
508
}
509
EOT;
510
511
        Admin::script($script);
512
    }
513
514
    /**
515
     * Disable create button.
516
     *
517
     * @return $this
518
     */
519
    public function disableCreate()
520
    {
521
        $this->options['allowCreate'] = false;
522
523
        return $this;
524
    }
525
526
    /**
527
     * Disable delete button.
528
     *
529
     * @return $this
530
     */
531
    public function disableDelete()
532
    {
533
        $this->options['allowDelete'] = false;
534
535
        return $this;
536
    }
537
538
    /**
539
     * Render the `HasMany` field.
540
     *
541
     * @throws \Exception
542
     *
543
     * @return \Illuminate\View\View
544
     */
545
    public function render()
546
    {
547
        // specify a view to render.
548
        $this->view = $this->views[$this->viewMode];
549
550
        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...
551
            ->getTemplateHtmlAndScript();
552
553
        $this->setupScript($script);
554
555
        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...
556
            'forms' => $this->buildRelatedForms(),
557
            'template' => $template,
558
            'relationName' => $this->relationName,
559
            'options' => $this->options,
560
        ]);
561
    }
562
}
563