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

HasMany::getKeyName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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