Completed
Pull Request — master (#3035)
by
unknown
02:45
created

HasMany::disableDelete()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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