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

HasMany::disableCreate()   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 0
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 View Code Duplication
        $array_key_clean_undot = function (array $a) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
122
            $keys = preg_grep('/[\.\:]/', array_keys($a));
123
            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...
124
                foreach ($keys as $key) {
125
                    array_set($a, str_replace(':', '', $key), $a[$key]);
126
                    unset($a[$key]);
127
                }
128
            }
129
130
            return $a;
131
        };
132
133
        $input = array_only($input, $this->column);
134
        $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...
135
        $rel = $this->relationName;
136
        $rules = $attributes = [];
137
        $messages = [];
138
        // remove all inputs & keys marked as removed
139
        $availInput = array_filter(array_map(function ($v) {
140
            return $v[NestedForm::REMOVE_FLAG_NAME] ? null : $v;
141
        }, $input[$rel]));
142
        $keys = array_keys($availInput);
143
        /* @var Field $field */
144
        foreach ($form->fields() as $field) {
145
            if (!$fieldRules = $field->getRules()) {
146
                continue;
147
            }
148
            $column = $field->column();
149
            $columns = is_array($column) ? $column : [$column];
150
            if ($field instanceof Field\MultipleSelect) {
151
                foreach ($keys as $key) {
152
                    $availInput[$key][$column] = array_filter($availInput[$key][$column], 'strlen');
153
                    $availInput[$key][$column] = $availInput[$key][$column] ? : null;
154
                }
155
            }
156
            // if($field instanceof Field\File)
157
            // {
158
            //     dd(request());
159
            // }
160
            $newColumn = call_user_func_array('array_merge', array_map(function ($u) use ($columns, $rel) {
161
                return array_map(function ($k, $v) use ($u, $rel) {
162
                    //Fix ResetInput Function! A Headache Implementation!
163
                    return $k ? "{$rel}.{$u}.{$v}:{$k}" : "{$rel}.{$u}.{$v}";
164
                }, array_keys($columns), array_values($columns));
165
            }, $keys));
166
167
            $fieldRules = is_array($fieldRules) ? implode('|', $fieldRules) : $fieldRules;
168 View Code Duplication
            $newRules = array_map(function ($v) use ($fieldRules, $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...
169
                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...
170
                //Fix ResetInput Function! A Headache Implementation!
171
                $col = explode(':', $c)[0];
172
                if (!array_key_exists($col, $availInput[$k])) {
173
                    return [null => null];
174
                }
175
176
                if (is_array($availInput[$k][$col])) {
177
                    return call_user_func_array('array_merge', array_map(function ($u) use ($v, $fieldRules) {
178
                        return ["{$v}{$u}" => $fieldRules];
179
                    }, array_keys($availInput[$k][$col])));
180
                }
181
182
                return [$v => $fieldRules];
183
            }, $newColumn);
184
            $rules = array_merge(
185
                $rules,
186
                call_user_func_array(
187
                    'array_merge',
188
                    array_filter(
189
                        $newRules,
190
                        'strlen',
191
                        ARRAY_FILTER_USE_KEY
192
                    )
193
                )
194
            );
195
196
            $newAttributes = array_map(function ($v) use ($field, $availInput) {
197
                list($r, $k, $c) = explode('.', $v);
198
                //Fix ResetInput Function! A Headache Implementation!
199
                $col = explode(':', $c)[0];
200
                if (!array_key_exists($col, $availInput[$k])) {
201
                    return [null => null];
202
                }
203
204
                if (is_array($availInput[$k][$col])) {
205 View Code Duplication
                    return call_user_func_array('array_merge', array_map(function ($u) use ($v, $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...
206
                        $w = $field->label();
207
                        //Fix ResetInput Function! A Headache Implementation!
208
                        $w .= is_array($field->column()) ? '[' . explode(':', explode('.', $v)[1])[0] . ']' : '';
209
                        return ["{$v}{$u}" => $w];
210
                    }, array_keys($$availInput[$k][$col])));
211
                }
212
213
                $w = $field->label();
214
                //Fix ResetInput Function! A Headache Implementation!
215
                $w .= is_array($field->column()) ? '[' . explode(':', explode('.', $v)[1])[0] . ']' : '';
216
217
                return [$v => $w];
218
            }, $newColumn);
219
            $attributes = array_merge(
220
                $attributes,
221
                call_user_func_array(
222
                    'array_merge',
223
                    array_filter(
224
                        $newAttributes,
225
                        'strlen',
226
                        ARRAY_FILTER_USE_KEY
227
                    )
228
                )
229
            );
230
231 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...
232
                $newMessages = array_map(function ($v) use ($field, $availInput, $array_key_attach_str) {
233
                    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...
234
                    //Fix ResetInput Function! A Headache Implementation!
235
                    $col1 = explode(':', $c)[0];
236
                    if (!array_key_exists($col1, $availInput[$k])) {
237
                        return [null => null];
238
                    }
239
                    $rows = $availInput[$k][$col1];
240
                    if (!is_array($rows)) {
241
                        return $array_key_attach_str($field->validationMessages, $v);
242
                    }
243
                    $r = [];
244
                    foreach (array_keys($rows) as $k) {
245
                        $k = "{$v}{$k}";
246
                        $r = array_merge($r, $array_key_attach_str($field->validationMessages, $k));
247
                    }
248
249
                    return $r;
250
                }, $newColumn);
251
                $newMessages = call_user_func_array('array_merge', $newMessages);
252
                $messages = array_merge($messages, $newMessages);
253
            }
254
        }
255
256
        if (empty($rules)) {
257
            return false;
258
        }
259
260
        $newInput = call_user_func_array('array_merge', array_map(function ($u) use ($availInput) {
261
            list($rel, $key, $col) = explode('.', $u);
262
            $idx = "{$rel}.{$key}.{$col}";
263
            //Fix ResetInput Function! A Headache Implementation!
264
            $col1 = explode(':', $col)[0];
265
            if (!array_key_exists($col1, $availInput[$key])) {
266
                return [null => null];
267
            }
268
            if (is_array($availInput[$key][$col1])) {
269
                return call_user_func_array('array_merge', array_map(function ($x, $y) use ($idx) {
270
                    return ["{$idx}{$x}" => $y];
271
                }, array_keys($availInput[$key][$col1]), $availInput[$key][$col1]));
272
            }
273
274
            return ["{$idx}" => $availInput[$key][$col1]];
275
        }, array_keys($rules)));
276
        $newInput = $array_key_clean_undot($newInput);
277
        $newRules = $array_key_clean($newRules);
0 ignored issues
show
Bug introduced by
The variable $newRules does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
278
        $newAttributes = $array_key_clean($newAttributes);
0 ignored issues
show
Bug introduced by
The variable $newAttributes does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

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