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

HasMany::setupScriptForDefaultView()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 34

Duplication

Lines 34
Ratio 100 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 34
loc 34
rs 9.376
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 View Code Duplication
if (!function_exists('Encore\Admin\Form\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...
15
    function array_key_attach_str(array $a, string $b, string $c = '.')
0 ignored issues
show
Best Practice introduced by
The function Encore\Admin\Form\Field\array_key_attach_str() has been defined more than once; this definition is ignored, only the first definition in src/Form/Field/Embeds.php (L10-18) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
16
    {
17
        return call_user_func_array(
18
            'array_merge',
19
            array_map(function ($u, $v) use ($b, $c) {
20
                return ["{$b}{$c}{$u}" => $v];
21
            }, array_keys($a), array_values($a))
22
        );
23
    };
24
}
25
26
if (!function_exists('Encore\Admin\Form\Field\array_clean_merge')) {
27
    function array_clean_merge(array $a, $b)
0 ignored issues
show
Best Practice introduced by
The function Encore\Admin\Form\Field\array_clean_merge() has been defined more than once; this definition is ignored, only the first definition in src/Form/Field/Embeds.php (L22-25) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
28
    {
29
        return $b ? array_merge($a, call_user_func_array('array_merge', $b)) : $a;
30
    };
31
}
32
33 View Code Duplication
if (!function_exists('Encore\Admin\Form\Field\array_key_clean_undot')) {
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...
34
    function array_key_clean_undot(array $a)
0 ignored issues
show
Best Practice introduced by
The function Encore\Admin\Form\Field\array_key_clean_undot() has been defined more than once; this definition is ignored, only the first definition in src/Form/Field/Embeds.php (L29-40) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
35
    {
36
        $keys = preg_grep('/[\.\:]/', array_keys($a));
37
        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...
38
            foreach ($keys as $key) {
39
                array_set($a, str_replace(':', '', $key), $a[$key]);
40
                unset($a[$key]);
41
            }
42
        }
43
44
        return $a;
45
    };
46
}
47
48 View Code Duplication
if (!function_exists('Encore\Admin\Form\Field\array_key_clean')) {
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...
49
    function array_key_clean(array $a)
0 ignored issues
show
Best Practice introduced by
The function Encore\Admin\Form\Field\array_key_clean() has been defined more than once; this definition is ignored, only the first definition in src/Form/Field/Embeds.php (L44-51) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
50
    {
51
        $a = count($a) ? call_user_func_array('array_merge', array_map(function ($k, $v) {
52
            return [str_replace(':', '', $k) => $v];
53
        }, array_keys($a), array_values($a))) : $a;
54
55
        return $a;
56
    };
57
}
58
59
/**
60
 * Class HasMany.
61
 */
62
class HasMany extends Field
63
{
64
    /**
65
     * Relation name.
66
     *
67
     * @var string
68
     */
69
    protected $relationName = '';
70
71
    /**
72
     * Form builder.
73
     *
74
     * @var \Closure
75
     */
76
    protected $builder = null;
77
78
    /**
79
     * Form data.
80
     *
81
     * @var array
82
     */
83
    protected $value = [];
84
85
    /**
86
     * View Mode.
87
     *
88
     * Supports `default` and `tab` currently.
89
     *
90
     * @var string
91
     */
92
    protected $viewMode = 'default';
93
94
    /**
95
     * Available views for HasMany field.
96
     *
97
     * @var array
98
     */
99
    protected $views = [
100
        'default' => 'admin::form.hasmany',
101
        'tab'     => 'admin::form.hasmanytab',
102
        'table'   => 'admin::form.hasmanytable',
103
    ];
104
105
    /**
106
     * Options for template.
107
     *
108
     * @var array
109
     */
110
    protected $options = [
111
        'allowCreate' => true,
112
        'allowDelete' => true,
113
    ];
114
115
    /**
116
     * Create a new HasMany field instance.
117
     *
118
     * @param $relationName
119
     * @param array $arguments
120
     */
121 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...
122
    {
123
        $this->relationName = $relationName;
124
125
        $this->column = $relationName;
126
127
        if (count($arguments) == 1) {
128
            $this->label = $this->formatLabel();
129
            $this->builder = $arguments[0];
130
        }
131
132
        if (count($arguments) == 2) {
133
            list($this->label, $this->builder) = $arguments;
134
        }
135
    }
136
137
    /**
138
     * Get validator for this field.
139
     *
140
     * @param array $input
141
     *
142
     * @return bool|Validator
143
     */
144
    public function getValidator(array $input)
145
    {
146
        if (!array_key_exists($this->column, $input)) {
147
            return false;
148
        }
149
150
        $input = array_only($input, $this->column);
151
        $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...
152
        $rel = $this->relationName;
153
        $rules = $attributes = $messages = $newInputs = [];
154
        // remove all inputs & keys marked as removed
155
        $availInput = array_filter(array_map(function ($v) {
156
            return $v[NestedForm::REMOVE_FLAG_NAME] ? null : $v;
157
        }, $input[$rel]));
158
        $keys = array_keys($availInput);
159
        /* @var Field $field */
160
        foreach ($form->fields() as $field) {
161
            if ($field instanceof Field\HasMany) {
162
                throw new \Exception('nested hasMany field found.');
163
            }
164
            if (!($field instanceof Field\Embeds) && !($fieldRules = $field->getRules())) {
165
                continue;
166
            }
167
            $column = $field->column();
168
            $columns = is_array($column) ? $column : [$column];
169 View Code Duplication
            if (
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...
170
                $field instanceof Field\MultipleSelect
171
                || $field instanceof Field\Listbox
172
                || $field instanceof Field\Checkbox
173
                || $field instanceof Field\Tags
174
                || $field instanceof Field\MultipleImage
175
                || $field instanceof Field\MultipleFile
176
            ) {
177
                foreach ($keys as $key) {
178
                    $availInput[$key][$column] = array_filter($availInput[$key][$column], 'strlen') ?: null;
179
                }
180
            }
181
182
            $newColumn = call_user_func_array('array_merge', array_map(function ($u) use ($columns, $rel) {
183
                return array_map(function ($k, $v) use ($u, $rel) {
184
                    //Fix ResetInput Function! A Headache Implementation!
185
                    return $k ? "{$rel}.{$u}.{$v}:{$k}" : "{$rel}.{$u}.{$v}";
186
                }, array_keys($columns), array_values($columns));
187
            }, $keys));
188
189
            if ($field instanceof Field\Embeds) {
190 View Code Duplication
                $newRules = array_map(function ($v) use ($availInput, $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...
191
                    list($r, $k, $c) = explode('.', $v);
192
                    $v = "{$r}.{$k}";
193
                    $embed = $field->getValidationRules([$field->column() => $availInput[$k][$c]]);
194
195
                    return $embed ? array_key_attach_str($embed, $v) : null;
196
                }, $newColumn);
197
                $rules = array_clean_merge($rules, array_filter($newRules));
198
199 View Code Duplication
                $newAttributes = array_map(function ($v) use ($availInput, $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...
200
                    list($r, $k, $c) = explode('.', $v);
201
                    $v = "{$r}.{$k}";
202
                    $embed = $field->getValidationAttributes([$field->column() => $availInput[$k][$c]]);
203
204
                    return $embed ? array_key_attach_str($embed, $v) : null;
205
                }, $newColumn);
206
                $attributes = array_clean_merge($attributes, array_filter($newAttributes));
207
208 View Code Duplication
                $newInput = array_map(function ($v) use ($availInput, $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...
209
                    list($r, $k, $c) = explode('.', $v);
210
                    $v = "{$r}.{$k}";
211
                    $embed = $field->getValidationInput([$field->column() => $availInput[$k][$c]]);
212
213
                    return $embed ? array_key_attach_str($embed, $v) : [null => 'null'];
214
                }, $newColumn);
215
                $newInputs = array_clean_merge($newInputs, array_filter($newInput, 'strlen', ARRAY_FILTER_USE_KEY));
216
217 View Code Duplication
                $newMessages = array_map(function ($v) use ($availInput, $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...
218
                    list($r, $k, $c) = explode('.', $v);
219
                    $v = "{$r}.{$k}";
220
                    $embed = $field->getValidationMessages([$field->column() => $availInput[$k][$c]]);
221
222
                    return $embed ? array_key_attach_str($embed, $v) : null;
223
                }, $newColumn);
224
                $messages = array_clean_merge($messages, array_filter($newMessages));
225
            } else {
226
                $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...
227 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...
228
                    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...
229
                    //Fix ResetInput Function! A Headache Implementation!
230
                    $col = explode(':', $c)[0];
231
                    if (array_key_exists($col, $availInput[$k]) && is_array($availInput[$k][$col])) {
232
                        return array_key_attach_str(preg_replace('/.+/', $fieldRules, $availInput[$k][$col]), $v, ':');
233
                    }
234
235
                    return [$v => $fieldRules];
236
                }, $newColumn);
237
                $rules = array_clean_merge($rules, $newRules);
238
239 View Code Duplication
                $newInput = array_map(function ($v) use ($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...
240
                    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...
241
                    //Fix ResetInput Function! A Headache Implementation!
242
                    $col = explode(':', $c)[0];
243
                    if (!array_key_exists($col, $availInput[$k])) {
244
                        return [$v => null];
245
                    }
246
247
                    if (is_array($availInput[$k][$col])) {
248
                        return array_key_attach_str($availInput[$k][$col], $v, ':');
249
                    }
250
251
                    return [$v => $availInput[$k][$col]];
252
                }, $newColumn);
253
                $newInputs = array_clean_merge($newInputs, $newInput);
254
255 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...
256
                    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...
257
                    //Fix ResetInput Function! A Headache Implementation!
258
                    $col = explode(':', $c)[0];
259
                    if (array_key_exists($col, $availInput[$k]) && is_array($availInput[$k][$col])) {
260
                        return call_user_func_array('array_merge', array_map(function ($u) use ($v, $field) {
261
                            $w = $field->label();
262
                            //Fix ResetInput Function! A Headache Implementation!
263
                            $w .= is_array($field->column()) ? '[' . explode(':', explode('.', $v)[2])[0] . ']' : '';
264
265
                            return ["{$v}:{$u}" => $w];
266
                        }, array_keys($availInput[$k][$col])));
267
                    }
268
269
                    $w = $field->label();
270
                    //Fix ResetInput Function! A Headache Implementation!
271
                    $w .= is_array($field->column()) ? '[' . explode(':', explode('.', $v)[2])[0] . ']' : '';
272
273
                    return [$v => $w];
274
                }, $newColumn);
275
                $attributes = array_clean_merge($attributes, $newAttributes);
276
            }
277
278 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...
279
                $newMessages = array_map(function ($v) use ($field, $availInput) {
280
                    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...
281
                    //Fix ResetInput Function! A Headache Implementation!
282
                    $col = explode(':', $c)[0];
283
                    if (array_key_exists($col, $availInput[$k]) && is_array($availInput[$k][$col])) {
284
                        return call_user_func_array('array_merge', array_map(function ($u) use ($v, $field) {
285
                            return array_key_attach_str($field->validationMessages, "{$v}:{$u}");
286
                        }, array_keys($availInput[$k][$col])));
287
                    }
288
289
                    return array_key_attach_str($field->validationMessages, $v);
290
                }, $newColumn);
291
                $messages = array_clean_merge($messages, $newMessages);
292
            }
293
        }
294
295
        $rules = array_filter($rules, 'strlen');
296
        if (empty($rules)) {
297
            return false;
298
        }
299
300
        $input = array_key_clean_undot(array_filter($newInputs, 'strlen', ARRAY_FILTER_USE_KEY));
301
        $rules = array_key_clean($rules);
302
        $attributes = array_key_clean($attributes);
303
        $messages = array_key_clean($messages);
304
305
        if (empty($input)) {
306
            $input = [$rel => $availInput];
307
        }
308
309
        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...
310
    }
311
312
313
    /**
314
     * Prepare input data for insert or update.
315
     *
316
     * @param array $input
317
     *
318
     * @return array
319
     */
320
    public function prepare($input)
321
    {
322
        $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...
323
324
        return $form->setOriginal($this->original, $this->getKeyName())->prepare($input);
325
    }
326
327
    /**
328
     * Build a Nested form.
329
     *
330
     * @param string   $column
331
     * @param \Closure $builder
332
     * @param null     $key
333
     *
334
     * @return NestedForm
335
     */
336
    protected function buildNestedForm($column, \Closure $builder, $key = null)
337
    {
338
        $form = new Form\NestedForm($column, $key);
339
340
        $form->setForm($this->form);
341
342
        call_user_func($builder, $form);
343
344
        $form->hidden($this->getKeyName());
345
346
        $form->hidden(NestedForm::REMOVE_FLAG_NAME)->default(0)->addElementClass(NestedForm::REMOVE_FLAG_CLASS);
347
348
        return $form;
349
    }
350
351
    /**
352
     * Get the HasMany relation key name.
353
     *
354
     * @return string
355
     */
356
    protected function getKeyName()
357
    {
358
        if (is_null($this->form)) {
359
            return;
360
        }
361
362
        return $this->form->model()->{$this->relationName}()->getRelated()->getKeyName();
363
    }
364
365
    /**
366
     * Set view mode.
367
     *
368
     * @param string $mode currently support `tab` mode.
369
     *
370
     * @return $this
371
     *
372
     * @author Edwin Hui
373
     */
374
    public function mode($mode)
375
    {
376
        $this->viewMode = $mode;
377
378
        return $this;
379
    }
380
381
    /**
382
     * Use tab mode to showing hasmany field.
383
     *
384
     * @return HasMany
385
     */
386
    public function useTab()
387
    {
388
        return $this->mode('tab');
389
    }
390
391
    /**
392
     * Use table mode to showing hasmany field.
393
     *
394
     * @return HasMany
395
     */
396
    public function useTable()
397
    {
398
        return $this->mode('table');
399
    }
400
401
    /**
402
     * Build Nested form for related data.
403
     *
404
     * @throws \Exception
405
     *
406
     * @return array
407
     */
408
    protected function buildRelatedForms()
409
    {
410
        if (is_null($this->form)) {
411
            return [];
412
        }
413
414
        $model = $this->form->model();
415
416
        $relation = call_user_func([$model, $this->relationName]);
417
418
        if (!$relation instanceof Relation && !$relation instanceof MorphMany) {
419
            throw new \Exception('hasMany field must be a HasMany or MorphMany relation.');
420
        }
421
422
        $forms = [];
423
424
        /*
425
         * If redirect from `exception` or `validation error` page.
426
         *
427
         * Then get form data from session flash.
428
         *
429
         * Else get data from database.
430
         */
431
        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...
432
            foreach ($values as $key => $data) {
433
                if ($data[NestedForm::REMOVE_FLAG_NAME] == 1) {
434
                    continue;
435
                }
436
437
                $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...
438
                    ->fill($data);
439
            }
440
        } else {
441
            foreach ($this->value as $data) {
442
                $key = array_get($data, $relation->getRelated()->getKeyName());
443
444
                $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...
445
                    ->fill($data);
446
            }
447
        }
448
449
        return $forms;
450
    }
451
452
    /**
453
     * Setup script for this field in different view mode.
454
     *
455
     * @param string $script
456
     *
457
     * @return void
458
     */
459
    protected function setupScript($script)
460
    {
461
        $method = 'setupScriptFor' . ucfirst($this->viewMode) . 'View';
462
463
        call_user_func([$this, $method], $script);
464
    }
465
466
    /**
467
     * Setup default template script.
468
     *
469
     * @param string $templateScript
470
     *
471
     * @return void
472
     */
473 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...
474
    {
475
        $removeClass = NestedForm::REMOVE_FLAG_CLASS;
476
        $defaultKey = NestedForm::DEFAULT_KEY_NAME;
477
478
        /**
479
         * When add a new sub form, replace all element key in new sub form.
480
         *
481
         * @example comments[new___key__][title]  => comments[new_{index}][title]
482
         *
483
         * {count} is increment number of current sub form count.
484
         */
485
        $script = <<<EOT
486
var index = 0;
487
$('#has-many-{$this->column}').on('click', '.add', function () {
488
489
    var tpl = $('template.{$this->column}-tpl');
490
491
    index++;
492
493
    var template = tpl.html().replace(/{$defaultKey}/g, index);
494
    $('.has-many-{$this->column}-forms').append(template);
495
    {$templateScript}
496
});
497
498
$('#has-many-{$this->column}').on('click', '.remove', function () {
499
    $(this).closest('.has-many-{$this->column}-form').hide();
500
    $(this).closest('.has-many-{$this->column}-form').find('.$removeClass').val(1);
501
});
502
503
EOT;
504
505
        Admin::script($script);
506
    }
507
508
    /**
509
     * Setup tab template script.
510
     *
511
     * @param string $templateScript
512
     *
513
     * @return void
514
     */
515 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...
516
    {
517
        $removeClass = NestedForm::REMOVE_FLAG_CLASS;
518
        $defaultKey = NestedForm::DEFAULT_KEY_NAME;
519
520
        $script = <<<EOT
521
522
$('#has-many-{$this->column} > .nav').off('click', 'i.close-tab').on('click', 'i.close-tab', function(){
523
    var \$navTab = $(this).siblings('a');
524
    var \$pane = $(\$navTab.attr('href'));
525
    if( \$pane.hasClass('new') ){
526
        \$pane.remove();
527
    }else{
528
        \$pane.removeClass('active').find('.$removeClass').val(1);
529
    }
530
    if(\$navTab.closest('li').hasClass('active')){
531
        \$navTab.closest('li').remove();
532
        $('#has-many-{$this->column} > .nav > li:nth-child(1) > a').tab('show');
533
    }else{
534
        \$navTab.closest('li').remove();
535
    }
536
});
537
538
var index = 0;
539
$('#has-many-{$this->column} > .header').off('click', '.add').on('click', '.add', function(){
540
    index++;
541
    var navTabHtml = $('#has-many-{$this->column} > template.nav-tab-tpl').html().replace(/{$defaultKey}/g, index);
542
    var paneHtml = $('#has-many-{$this->column} > template.pane-tpl').html().replace(/{$defaultKey}/g, index);
543
    $('#has-many-{$this->column} > .nav').append(navTabHtml);
544
    $('#has-many-{$this->column} > .tab-content').append(paneHtml);
545
    $('#has-many-{$this->column} > .nav > li:last-child a').tab('show');
546
    {$templateScript}
547
});
548
549
if ($('.has-error').length) {
550
    $('.has-error').parent('.tab-pane').each(function () {
551
        var tabId = '#'+$(this).attr('id');
552
        $('li a[href="'+tabId+'"] i').removeClass('hide');
553
    });
554
    
555
    var first = $('.has-error:first').parent().attr('id');
556
    $('li a[href="#'+first+'"]').tab('show');
557
}
558
EOT;
559
560
        Admin::script($script);
561
    }
562
563
    /**
564
     * Setup default template script.
565
     *
566
     * @param string $templateScript
567
     *
568
     * @return void
569
     */
570 View Code Duplication
    protected function setupScriptForTableView($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...
571
    {
572
        $removeClass = NestedForm::REMOVE_FLAG_CLASS;
573
        $defaultKey = NestedForm::DEFAULT_KEY_NAME;
574
575
        /**
576
         * When add a new sub form, replace all element key in new sub form.
577
         *
578
         * @example comments[new___key__][title]  => comments[new_{index}][title]
579
         *
580
         * {count} is increment number of current sub form count.
581
         */
582
        $script = <<<EOT
583
var index = 0;
584
$('#has-many-{$this->column}').on('click', '.add', function () {
585
586
    var tpl = $('template.{$this->column}-tpl');
587
588
    index++;
589
590
    var template = tpl.html().replace(/{$defaultKey}/g, index);
591
    $('.has-many-{$this->column}-forms').append(template);
592
    {$templateScript}
593
});
594
595
$('#has-many-{$this->column}').on('click', '.remove', function () {
596
    $(this).closest('.has-many-{$this->column}-form').hide();
597
    $(this).closest('.has-many-{$this->column}-form').find('.$removeClass').val(1);
598
});
599
600
EOT;
601
602
        Admin::script($script);
603
    }
604
605
    /**
606
     * Disable create button.
607
     *
608
     * @return $this
609
     */
610
    public function disableCreate()
611
    {
612
        $this->options['allowCreate'] = false;
613
614
        return $this;
615
    }
616
617
    /**
618
     * Disable delete button.
619
     *
620
     * @return $this
621
     */
622
    public function disableDelete()
623
    {
624
        $this->options['allowDelete'] = false;
625
626
        return $this;
627
    }
628
629
    /**
630
     * Render the `HasMany` field.
631
     *
632
     * @throws \Exception
633
     *
634
     * @return \Illuminate\View\View
635
     */
636
    public function render()
637
    {
638
        if ($this->viewMode == 'table') {
639
            return $this->renderTable();
640
        }
641
642
        // specify a view to render.
643
        $this->view = $this->views[$this->viewMode];
644
645
        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...
646
            ->getTemplateHtmlAndScript();
647
648
        $this->setupScript($script);
649
650
        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...
651
            'forms'        => $this->buildRelatedForms(),
652
            'template'     => $template,
653
            'relationName' => $this->relationName,
654
            'options'      => $this->options,
655
        ]);
656
    }
657
658
    /**
659
     * Render the `HasMany` field for table style.
660
     *
661
     * @throws \Exception
662
     *
663
     * @return mixed
664
     */
665
    protected function renderTable()
666
    {
667
        $headers = [];
668
        $fields = [];
669
        $hidden = [];
670
        $scripts = [];
671
672
        /* @var Field $field */
673
        foreach ($this->buildNestedForm($this->column, $this->builder)->fields() as $field) {
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...
674
            if (is_a($field, Hidden::class)) {
675
                $hidden[] = $field->render();
676
            } else {
677
                /* Hide label and set field width 100% */
678
                $field->setLabelClass(['hidden']);
679
                $field->setWidth(12, 0);
680
                $fields[] = $field->render();
681
                $headers[] = $field->label();
682
            }
683
684
            /*
685
             * Get and remove the last script of Admin::$script stack.
686
             */
687
            if ($field->getScript()) {
688
                $scripts[] = array_pop(Admin::$script);
689
            }
690
        }
691
692
        /* Build row elements */
693
        $template = array_reduce($fields, function ($all, $field) {
694
            $all .= "<td>{$field}</td>";
695
696
            return $all;
697
        }, '');
698
699
        /* Build cell with hidden elements */
700
        $template .= '<td class="hidden">' . implode('', $hidden) . '</td>';
701
702
        $this->setupScript(implode("\r\n", $scripts));
703
704
        // specify a view to render.
705
        $this->view = $this->views[$this->viewMode];
706
707
        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...
Comprehensibility Bug introduced by
It seems like you call parent on a different method (render() instead of renderTable()). Are you sure this is correct? If so, you might want to change this to $this->render().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
708
            'headers'      => $headers,
709
            'forms'        => $this->buildRelatedForms(),
710
            'template'     => $template,
711
            'relationName' => $this->relationName,
712
            'options'      => $this->options,
713
        ]);
714
    }
715
}
716