Completed
Pull Request — master (#2905)
by
unknown
03:06
created

HasMany::formatValidationAttribute()   B

Complexity

Conditions 8
Paths 9

Size

Total Lines 26

Duplication

Lines 26
Ratio 100 %

Importance

Changes 0
Metric Value
cc 8
nc 9
nop 3
dl 26
loc 26
rs 8.4444
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
        $input = array_only($input, $this->column);
136
        $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...
137
        $rel = $this->relationName;
138
        $rules = $attributes = $messages = $newInputs = [];
139
        // remove all inputs & keys marked as removed
140
        $availInput = array_filter(array_map(function ($v) {
141
            return $v[NestedForm::REMOVE_FLAG_NAME] ? null : $v;
142
        }, $input[$rel]));
143
        $keys = array_keys($availInput);
144
        /* @var Field $field */
145
        foreach ($form->fields() as $field) {
146
            if ($field instanceof Field\HasMany) {
147
                throw new \Exception('hasMany field CAN NOT build within a HasMany field.');
148
            }
149
            if (!($field instanceof Field\Embeds) && !($fieldRules = $field->getRules())) {
150
                continue;
151
            }
152
            $column = $field->column();
153
            $columns = is_array($column) ? $column : [$column];
154 View Code Duplication
            if ($field instanceof Field\MultipleSelect || $field instanceof Field\Listbox || $field instanceof Field\Tag) {
0 ignored issues
show
Bug introduced by
The class Encore\Admin\Form\Field\Tag does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
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...
155
                foreach ($keys as $key) {
156
                    $availInput[$key][$column] = array_filter($availInput[$key][$column], 'strlen') ?: null;
157
                }
158
            }
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
            if ($field instanceof Field\Embeds) {
168 View Code Duplication
                $newRules = array_map(function ($v) use ($availInput, $field, $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...
169
                    list($r, $k, $c) = explode('.', $v);
170
                    $v = "{$r}.{$k}";
171
                    $embed = $field->getValidationRules([$field->column() => $availInput[$k][$c]]);
172
                    return $embed ? $array_key_attach_str($embed, $v) : null;
173
                }, $newColumn);
174
                $rules = $array_clean_merge($rules, array_filter($newRules));
175
176 View Code Duplication
                $newAttributes = array_map(function ($v) use ($availInput, $field, $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...
177
                    list($r, $k, $c) = explode('.', $v);
178
                    $v = "{$r}.{$k}";
179
                    $embed = $field->getValidationAttributes([$field->column() => $availInput[$k][$c]]);
180
                    return $embed ? $array_key_attach_str($embed, $v) : null;
181
                }, $newColumn);
182
                $attributes = $array_clean_merge($attributes, array_filter($newAttributes));
183
184 View Code Duplication
                $newInput = array_map(function ($v) use ($availInput, $field, $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...
185
                    list($r, $k, $c) = explode('.', $v);
186
                    $v = "{$r}.{$k}";
187
                    $embed = $field->getValidationInput([$field->column() => $availInput[$k][$c]]);
188
                    return $embed ? $array_key_attach_str($embed, $v) : [null => 'null'];
189
                }, $newColumn);
190
                $newInputs = $array_clean_merge($newInputs, array_filter($newInput, 'strlen', ARRAY_FILTER_USE_KEY));
191
192 View Code Duplication
                $newMessages = array_map(function ($v) use ($availInput, $field, $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...
193
                    list($r, $k, $c) = explode('.', $v);
194
                    $v = "{$r}.{$k}";
195
                    $embed = $field->getValidationMessages([$field->column() => $availInput[$k][$c]]);
196
                    return $embed ? $array_key_attach_str($embed, $v) : null;
197
                }, $newColumn);
198
                $messages = $array_clean_merge($messages, array_filter($newMessages));
199
            } else {
200
                $fieldRules = is_array($fieldRules) ? implode('|', $fieldRules) : $fieldRules;
0 ignored issues
show
Bug introduced by
The variable $fieldRules 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...
201 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...
202
                    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...
203
                    //Fix ResetInput Function! A Headache Implementation!
204
                    $col = explode(':', $c)[0];
205
                    if (array_key_exists($col, $availInput[$k]) && is_array($availInput[$k][$col])) {
206
                        return $array_key_attach_str(preg_replace('/.+/', $fieldRules, $availInput[$k][$col]), $v, ':');
207
                    }
208
209
                    return [$v => $fieldRules];
210
                }, $newColumn);
211
                $rules = $array_clean_merge($rules, $newRules);
212
213 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...
214
                    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...
215
                    //Fix ResetInput Function! A Headache Implementation!
216
                    $col = explode(':', $c)[0];
217
                    if (!array_key_exists($col, $availInput[$k])) {
218
219
                        return [$v => null];
220
                    }
221
222
                    if (is_array($availInput[$k][$col])) {
223
                        return $array_key_attach_str($availInput[$k][$col], $v, ':');
224
                    }
225
226
                    return [$v => $availInput[$k][$col]];
227
                }, $newColumn);
228
                $newInputs = $array_clean_merge($newInputs, $newInput);
229
230 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...
231
                    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...
232
                    //Fix ResetInput Function! A Headache Implementation!
233
                    $col = explode(':', $c)[0];
234
                    if (array_key_exists($col, $availInput[$k]) && is_array($availInput[$k][$col])) {
235
                        return call_user_func_array('array_merge', array_map(function ($u) use ($v, $field) {
236
                            $w = $field->label();
237
                            //Fix ResetInput Function! A Headache Implementation!
238
                            $w .= is_array($field->column()) ? '['.explode(':', explode('.', $v)[2])[0].']' : '';
239
240
                            return ["{$v}:{$u}" => $w];
241
                        }, array_keys($availInput[$k][$col])));
242
                    }
243
244
                    $w = $field->label();
245
                    //Fix ResetInput Function! A Headache Implementation!
246
                    $w .= is_array($field->column()) ? '['.explode(':', explode('.', $v)[2])[0].']' : '';
247
248
                    return [$v => $w];
249
                }, $newColumn);
250
                $attributes = $array_clean_merge($attributes, $newAttributes);
251
            }
252
253 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...
254
                $newMessages = array_map(function ($v) use ($field, $availInput, $array_key_attach_str) {
255
                    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...
256
                    //Fix ResetInput Function! A Headache Implementation!
257
                    $col = explode(':', $c)[0];
258
                    if (array_key_exists($col, $availInput[$k]) && is_array($availInput[$k][$col])) {
259
                        return call_user_func_array('array_merge', array_map(function ($u) use ($v, $field, $array_key_attach_str) {
260
                            return $array_key_attach_str($field->validationMessages, "{$v}:{$u}");
261
                        }, array_keys($availInput[$k][$col])));
262
                    }
263
264
                    return $array_key_attach_str($field->validationMessages, $v);
265
                }, $newColumn);
266
                $messages = $array_clean_merge($messages, $newMessages);
267
            }
268
        }
269
270
        $rules = array_filter($rules, 'strlen');
271
        if (empty($rules)) {
272
            return false;
273
        }
274
275
        $input = $array_key_clean_undot(array_filter($newInputs, 'strlen', ARRAY_FILTER_USE_KEY));
276
        $rules = $array_key_clean($rules);
277
        $attributes = $array_key_clean($attributes);
278
        $messages = $array_key_clean($messages);
279
280
        if (empty($input)) {
281
            $input = [$rel => $availInput];
282
        }
283
284
        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...
285
    }
286
287
    /**
288
     * Prepare input data for insert or update.
289
     *
290
     * @param array $input
291
     *
292
     * @return array
293
     */
294
    public function prepare($input)
295
    {
296
        $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...
297
298
        return $form->setOriginal($this->original, $this->getKeyName())->prepare($input);
299
    }
300
301
    /**
302
     * Build a Nested form.
303
     *
304
     * @param string   $column
305
     * @param \Closure $builder
306
     * @param null     $key
307
     *
308
     * @return NestedForm
309
     */
310
    protected function buildNestedForm($column, \Closure $builder, $key = null)
311
    {
312
        $form = new Form\NestedForm($column, $key);
313
314
        $form->setForm($this->form);
315
316
        call_user_func($builder, $form);
317
318
        $form->hidden($this->getKeyName());
319
320
        $form->hidden(NestedForm::REMOVE_FLAG_NAME)->default(0)->addElementClass(NestedForm::REMOVE_FLAG_CLASS);
321
322
        return $form;
323
    }
324
325
    /**
326
     * Get the HasMany relation key name.
327
     *
328
     * @return string
329
     */
330
    protected function getKeyName()
331
    {
332
        if (is_null($this->form)) {
333
            return;
334
        }
335
336
        return $this->form->model()->{$this->relationName}()->getRelated()->getKeyName();
337
    }
338
339
    /**
340
     * Set view mode.
341
     *
342
     * @param string $mode currently support `tab` mode.
343
     *
344
     * @return $this
345
     *
346
     * @author Edwin Hui
347
     */
348
    public function mode($mode)
349
    {
350
        $this->viewMode = $mode;
351
352
        return $this;
353
    }
354
355
    /**
356
     * Use tab mode to showing hasmany field.
357
     *
358
     * @return HasMany
359
     */
360
    public function useTab()
361
    {
362
        return $this->mode('tab');
363
    }
364
365
    /**
366
     * Build Nested form for related data.
367
     *
368
     * @throws \Exception
369
     *
370
     * @return array
371
     */
372
    protected function buildRelatedForms()
373
    {
374
        if (is_null($this->form)) {
375
            return [];
376
        }
377
378
        $model = $this->form->model();
379
380
        $relation = call_user_func([$model, $this->relationName]);
381
382
        if (!$relation instanceof Relation && !$relation instanceof MorphMany) {
383
            throw new \Exception('hasMany field must be a HasMany or MorphMany relation.');
384
        }
385
386
        $forms = [];
387
388
        /*
389
         * If redirect from `exception` or `validation error` page.
390
         *
391
         * Then get form data from session flash.
392
         *
393
         * Else get data from database.
394
         */
395
        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...
396
            foreach ($values as $key => $data) {
397
                if ($data[NestedForm::REMOVE_FLAG_NAME] == 1) {
398
                    continue;
399
                }
400
401
                $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...
402
                    ->fill($data);
403
            }
404
        } else {
405
            foreach ($this->value as $data) {
406
                $key = array_get($data, $relation->getRelated()->getKeyName());
407
408
                $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...
409
                    ->fill($data);
410
            }
411
        }
412
413
        return $forms;
414
    }
415
416
    /**
417
     * Setup script for this field in different view mode.
418
     *
419
     * @param string $script
420
     *
421
     * @return void
422
     */
423
    protected function setupScript($script)
424
    {
425
        $method = 'setupScriptFor'.ucfirst($this->viewMode).'View';
426
427
        call_user_func([$this, $method], $script);
428
    }
429
430
    /**
431
     * Setup default template script.
432
     *
433
     * @param string $templateScript
434
     *
435
     * @return void
436
     */
437 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...
438
    {
439
        $removeClass = NestedForm::REMOVE_FLAG_CLASS;
440
        $defaultKey = NestedForm::DEFAULT_KEY_NAME;
441
442
        /**
443
         * When add a new sub form, replace all element key in new sub form.
444
         *
445
         * @example comments[new___key__][title]  => comments[new_{index}][title]
446
         *
447
         * {count} is increment number of current sub form count.
448
         */
449
        $script = <<<EOT
450
var index = 0;
451
$('#has-many-{$this->column}').on('click', '.add', function() {
452
453
    var tpl = $('template.{$this->column}-tpl');
454
455
    index++;
456
457
    var template = tpl.html().replace(/{$defaultKey}/g, index);
458
    $('.has-many-{$this->column}-forms').append(template);
459
    {$templateScript}
460
});
461
462
$('#has-many-{$this->column}').on('click', '.remove', function() {
463
    $(this).closest('.has-many-{$this->column}-form').hide();
464
    $(this).closest('.has-many-{$this->column}-form').find('.$removeClass').val(1);
465
});
466
467
EOT;
468
469
        Admin::script($script);
470
    }
471
472
    /**
473
     * Setup tab template script.
474
     *
475
     * @param string $templateScript
476
     *
477
     * @return void
478
     */
479 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...
480
    {
481
        $removeClass = NestedForm::REMOVE_FLAG_CLASS;
482
        $defaultKey = NestedForm::DEFAULT_KEY_NAME;
483
484
        $script = <<<EOT
485
486
$('#has-many-{$this->column} > .nav').off('click', 'i.close-tab').on('click', 'i.close-tab', function(){
487
    var \$navTab = $(this).siblings('a');
488
    var \$pane = $(\$navTab.attr('href'));
489
    if( \$pane.hasClass('new') ){
490
        \$pane.remove();
491
    }else{
492
        \$pane.removeClass('active').find('.$removeClass').val(1);
493
    }
494
    if(\$navTab.closest('li').hasClass('active')){
495
        \$navTab.closest('li').remove();
496
        $('#has-many-{$this->column} > .nav > li:nth-child(1) > a').tab('show');
497
    }else{
498
        \$navTab.closest('li').remove();
499
    }
500
});
501
502
var index = 0;
503
$('#has-many-{$this->column} > .header').off('click', '.add').on('click', '.add', function(){
504
    index++;
505
    var navTabHtml = $('#has-many-{$this->column} > template.nav-tab-tpl').html().replace(/{$defaultKey}/g, index);
506
    var paneHtml = $('#has-many-{$this->column} > template.pane-tpl').html().replace(/{$defaultKey}/g, index);
507
    $('#has-many-{$this->column} > .nav').append(navTabHtml);
508
    $('#has-many-{$this->column} > .tab-content').append(paneHtml);
509
    $('#has-many-{$this->column} > .nav > li:last-child a').tab('show');
510
    {$templateScript}
511
});
512
513
if ($('.has-error').length) {
514
    $('.has-error').parent('.tab-pane').each(function() {
515
        var tabId = '#'+$(this).attr('id');
516
        $('li a[href="'+tabId+'"] i').removeClass('hide');
517
    });
518
    
519
    var first = $('.has-error:first').parent().attr('id');
520
    $('li a[href="#'+first+'"]').tab('show');
521
}
522
EOT;
523
524
        Admin::script($script);
525
    }
526
527
    /**
528
     * Disable create button.
529
     *
530
     * @return $this
531
     */
532
    public function disableCreate()
533
    {
534
        $this->options['allowCreate'] = false;
535
536
        return $this;
537
    }
538
539
    /**
540
     * Disable delete button.
541
     *
542
     * @return $this
543
     */
544
    public function disableDelete()
545
    {
546
        $this->options['allowDelete'] = false;
547
548
        return $this;
549
    }
550
551
    /**
552
     * Render the `HasMany` field.
553
     *
554
     * @throws \Exception
555
     *
556
     * @return \Illuminate\View\View
557
     */
558
    public function render()
559
    {
560
        // specify a view to render.
561
        $this->view = $this->views[$this->viewMode];
562
563
        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...
564
            ->getTemplateHtmlAndScript();
565
566
        $this->setupScript($script);
567
568
        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...
569
            'forms'        => $this->buildRelatedForms(),
570
            'template'     => $template,
571
            'relationName' => $this->relationName,
572
            'options'      => $this->options,
573
        ]);
574
    }
575
}
576