Completed
Pull Request — master (#2905)
by
unknown
02:43
created

Embeds   F

Complexity

Total Complexity 70

Size/Duplication

Total Lines 510
Duplicated Lines 27.84 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
dl 142
loc 510
rs 2.8
c 0
b 0
f 0
wmc 70
lcom 1
cbo 4

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 13 13 3
A prepare() 0 6 1
C getValidationRules() 24 78 12
C getValidationAttributes() 33 87 13
C getValidationInput() 27 81 12
C getValidationMessages() 28 80 12
B getValidator() 17 46 7
A getEmbeddedData() 0 16 4
A buildEmbeddedForm() 0 34 5
A render() 0 4 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Embeds often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Embeds, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Encore\Admin\Form\Field;
4
5
use Encore\Admin\Form\EmbeddedForm;
6
use Encore\Admin\Form\Field;
7
use Illuminate\Support\Facades\Validator;
8
9
class Embeds extends Field
10
{
11
    /**
12
     * @var \Closure
13
     */
14
    protected $builder = null;
15
    protected $view = 'admin::form.embeds';
16
    /**
17
     * Create a new HasMany field instance.
18
     *
19
     * @param string $column
20
     * @param array  $arguments
21
     */
22 View Code Duplication
    public function __construct($column, $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...
23
    {
24
        $this->column = $column;
25
26
        if (count($arguments) == 1) {
27
            $this->label = $this->formatLabel();
28
            $this->builder = $arguments[0];
29
        }
30
31
        if (count($arguments) == 2) {
32
            list($this->label, $this->builder) = $arguments;
33
        }
34
    }
35
36
    /**
37
     * Prepare input data for insert or update.
38
     *
39
     * @param array $input
40
     *
41
     * @return array
42
     */
43
    public function prepare($input)
44
    {
45
        $form = $this->buildEmbeddedForm();
46
47
        return $form->setOriginal($this->original)->prepare($input);
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53
    public function getValidationRules(array $input)
54
    {
55
        if (!array_key_exists($this->column, $input)) {
56
            return false;
57
        }
58
59
        $input = array_only($input, $this->column);
60
        $rules = $attributes = $messages = $newInputs = [];
0 ignored issues
show
Unused Code introduced by
$newInputs is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
Unused Code introduced by
$messages is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
Unused Code introduced by
$attributes is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
61
        $rel = $this->column;
62
        $availInput = $input;
63 View Code Duplication
        $array_key_attach_str = function (array $a, string $b, string $c = '.') {
0 ignored issues
show
Unused Code introduced by
$array_key_attach_str is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
64
            return call_user_func_array(
65
                'array_merge',
66
                array_map(function ($u, $v) use ($b, $c) {
67
                    return ["{$b}{$c}{$u}" => $v];
68
                }, array_keys($a), array_values($a))
69
            );
70
        };
71
72
        $array_clean_merge = function (array $a, $b) {
73
            return array_merge($a, call_user_func_array('array_merge', $b));
74
        };
75
76
        /** @var Field $field */
77
        foreach ($this->buildEmbeddedForm()->fields() as $field) {
78
            if (!$fieldRules = $field->getRules()) {
79
                continue;
80
            }
81
82
            $column = $field->column();
83
            $columns = is_array($column) ? $column : [$column];
84 View Code Duplication
            if ($field instanceof Field\MultipleSelect || $field instanceof Field\Listbox) {
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...
85
                $availInput[$column] = array_filter($availInput[$column], 'strlen');
86
                $availInput[$column] = $availInput[$column] ? : null;
87
            }
88
            /*
89
             *
90
             * For single column field format rules to:
91
             * [
92
             *     'extra.name' => 'required'
93
             *     'extra.email' => 'required'
94
             * ]
95
             *
96
             * For multiple column field with rules like 'required':
97
             * 'extra' => [
98
             *     'start' => 'start_at'
99
             *     'end'   => 'end_at',
100
             * ]
101
             *
102
             * format rules to:
103
             * [
104
             *     'extra.start_atstart' => 'required'
105
             *     'extra.end_atend' => 'required'
106
             * ]
107
             */
108
            $newColumn = array_map(function ($k, $v) use ($rel) {
109
                //Fix ResetInput Function! A Headache Implementation!
110
                return !$k ? "{$rel}.{$v}" : "{$rel}.{$v}:{$k}";
111
            }, array_keys($columns), array_values($columns));
112
113
            $fieldRules = is_array($fieldRules) ? implode('|', $fieldRules) : $fieldRules;
114 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...
115
                list($k, $c) = explode('.', $v);
116
                //Fix ResetInput Function! A Headache Implementation!
117
                $col = explode(':', $c)[0];
118
119
                if (array_key_exists($col, $availInput[$k]) && is_array($availInput[$k][$col])) {
120
                    return $array_key_attach_str(preg_replace('/./', $fieldRules, $availInput[$k][$col]), $v, ':');
0 ignored issues
show
Bug introduced by
The variable $array_key_attach_str does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
121
                }
122
123
                //May Have Problem in Dealing with File Upload in Edit Mode
124
                return [$v => $fieldRules];
125
            }, $newColumn);
126
            $rules = $array_clean_merge($rules, $newRules);
127
        }
128
129
        return $rules;
130
    }
131
132
    /**
133
     * {@inheritdoc}
134
     */
135
    public function getValidationAttributes(array $input)
136
    {
137
        if (!array_key_exists($this->column, $input)) {
138
            return false;
139
        }
140
141
        $input = array_only($input, $this->column);
142
        $rules = $attributes = $messages = $newInputs = [];
0 ignored issues
show
Unused Code introduced by
$newInputs is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
Unused Code introduced by
$messages is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
Unused Code introduced by
$rules is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
143
        $rel = $this->column;
144
        $availInput = $input;
145 View Code Duplication
        $array_key_attach_str = function (array $a, string $b, string $c = '.') {
0 ignored issues
show
Unused Code introduced by
$array_key_attach_str is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
146
            return call_user_func_array(
147
                'array_merge',
148
                array_map(function ($u, $v) use ($b, $c) {
149
                    return ["{$b}{$c}{$u}" => $v];
150
                }, array_keys($a), array_values($a))
151
            );
152
        };
153
154
        $array_clean_merge = function (array $a, $b) {
155
            return array_merge($a, call_user_func_array('array_merge', $b));
156
        };
157
158
        /** @var Field $field */
159
        foreach ($this->buildEmbeddedForm()->fields() as $field) {
160
            if (!$fieldRules = $field->getRules()) {
161
                continue;
162
            }
163
164
            $column = $field->column();
165
            $columns = is_array($column) ? $column : [$column];
166 View Code Duplication
            if ($field instanceof Field\MultipleSelect || $field instanceof Field\Listbox) {
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...
167
                $availInput[$column] = array_filter($availInput[$column], 'strlen');
168
                $availInput[$column] = $availInput[$column] ? : null;
169
            }
170
            /*
171
             *
172
             * For single column field format rules to:
173
             * [
174
             *     'extra.name' => 'required'
175
             *     'extra.email' => 'required'
176
             * ]
177
             *
178
             * For multiple column field with rules like 'required':
179
             * 'extra' => [
180
             *     'start' => 'start_at'
181
             *     'end'   => 'end_at',
182
             * ]
183
             *
184
             * format rules to:
185
             * [
186
             *     'extra.start_atstart' => 'required'
187
             *     'extra.end_atend' => 'required'
188
             * ]
189
             */
190
            $newColumn = array_map(function ($k, $v) use ($rel) {
191
                //Fix ResetInput Function! A Headache Implementation!
192
                return !$k ? "{$rel}.{$v}" : "{$rel}.{$v}:{$k}";
193
            }, array_keys($columns), array_values($columns));
194
195 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...
196
                list($k, $c) = explode('.', $v);
197
                //Fix ResetInput Function! A Headache Implementation!
198
                $col = explode(':', $c)[0];
199
                if (array_key_exists($col, $availInput[$k]) && is_array($availInput[$k][$col])) {
200
                    return call_user_func_array('array_merge', array_map(function ($u) use ($v, $field) {
201
                        $w = $field->label();
202
                        //Fix ResetInput Function! A Headache Implementation!
203
                        $w .= is_array($field->column()) ? '[' . explode(':', explode('.', $v)[2])[0] . ']' : '';
204
205
                        return ["{$v}:{$u}" => $w];
206
                    }, array_keys($availInput[$k][$col])));
207
                }
208
209
                //May Have Problem in Dealing with File Upload in Edit Mode
210
                $w = $field->label();
211
                //Fix ResetInput Function! A Headache Implementation!
212
                $w .= is_array($field->column()) ? '[' . explode(':', explode('.', $v)[2])[0] . ']' : '';
213
214
                return [$v => $w];
215
            }, $newColumn);
216
            $attributes = $array_clean_merge($attributes, $newAttributes);
217
218
        }
219
220
        return $attributes;
221
    }
222
223
    /**
224
     * {@inheritdoc}
225
     */
226
    public function getValidationInput(array $input)
227
    {
228
        if (!array_key_exists($this->column, $input)) {
229
            return false;
230
        }
231
232
        $input = array_only($input, $this->column);
233
        $rules = $attributes = $messages = $newInputs = [];
0 ignored issues
show
Unused Code introduced by
$messages is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
Unused Code introduced by
$attributes is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
Unused Code introduced by
$rules is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
234
        $rel = $this->column;
235
        $availInput = $input;
236 View Code Duplication
        $array_key_attach_str = function (array $a, string $b, string $c = '.') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
237
            return call_user_func_array(
238
                'array_merge',
239
                array_map(function ($u, $v) use ($b, $c) {
240
                    return ["{$b}{$c}{$u}" => $v];
241
                }, array_keys($a), array_values($a))
242
            );
243
        };
244
245
        $array_clean_merge = function (array $a, $b) {
246
            return array_merge($a, call_user_func_array('array_merge', $b));
247
        };
248
249
        /** @var Field $field */
250
        foreach ($this->buildEmbeddedForm()->fields() as $field) {
251
            if (!$fieldRules = $field->getRules()) {
252
                continue;
253
            }
254
255
            $column = $field->column();
256
            $columns = is_array($column) ? $column : [$column];
257 View Code Duplication
            if ($field instanceof Field\MultipleSelect || $field instanceof Field\Listbox) {
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...
258
                $availInput[$column] = array_filter($availInput[$column], 'strlen');
259
                $availInput[$column] = $availInput[$column] ? : null;
260
            }
261
            /*
262
             *
263
             * For single column field format rules to:
264
             * [
265
             *     'extra.name' => 'required'
266
             *     'extra.email' => 'required'
267
             * ]
268
             *
269
             * For multiple column field with rules like 'required':
270
             * 'extra' => [
271
             *     'start' => 'start_at'
272
             *     'end'   => 'end_at',
273
             * ]
274
             *
275
             * format rules to:
276
             * [
277
             *     'extra.start_atstart' => 'required'
278
             *     'extra.end_atend' => 'required'
279
             * ]
280
             */
281
            $newColumn = array_map(function ($k, $v) use ($rel) {
282
                //Fix ResetInput Function! A Headache Implementation!
283
                return !$k ? "{$rel}.{$v}" : "{$rel}.{$v}:{$k}";
284
            }, array_keys($columns), array_values($columns));
285
286 View Code Duplication
            $newInput = array_map(function ($v) use ($availInput, $array_key_attach_str) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
287
                list($k, $c) = explode('.', $v);
288
                //Fix ResetInput Function! A Headache Implementation!
289
                $col = explode(':', $c)[0];
290
                if (!array_key_exists($col, $availInput[$k])) {
291
                    //May Have Problem in Dealing with File Upload in Edit Mode
292
                    return [$v => null];
293
                }
294
295
                if (array_key_exists($col, $availInput[$k]) && is_array($availInput[$k][$col])) {
296
                    return $array_key_attach_str($availInput[$k][$col], $v, ':');
297
                }
298
299
                return [$v => $availInput[$k][$col]];
300
            }, $newColumn);
301
            $newInputs = $array_clean_merge($newInputs, $newInput);
302
303
        }
304
305
        return $newInputs;
306
    }
307
308
    /**
309
     * {@inheritdoc}
310
     */
311
    public function getValidationMessages(array $input)
312
    {
313
        if (!array_key_exists($this->column, $input)) {
314
            return false;
315
        }
316
317
        $input = array_only($input, $this->column);
318
        $rules = $attributes = $messages = $newInputs = [];
0 ignored issues
show
Unused Code introduced by
$newInputs is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
Unused Code introduced by
$attributes is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
Unused Code introduced by
$rules is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
319
        $rel = $this->column;
320
        $availInput = $input;
321 View Code Duplication
        $array_key_attach_str = function (array $a, string $b, string $c = '.') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
322
            return call_user_func_array(
323
                'array_merge',
324
                array_map(function ($u, $v) use ($b, $c) {
325
                    return ["{$b}{$c}{$u}" => $v];
326
                }, array_keys($a), array_values($a))
327
            );
328
        };
329
330
        $array_clean_merge = function (array $a, $b) {
331
            return array_merge($a, call_user_func_array('array_merge', $b));
332
        };
333
334
        /** @var Field $field */
335
        foreach ($this->buildEmbeddedForm()->fields() as $field) {
336
            if (!$fieldRules = $field->getRules()) {
337
                continue;
338
            }
339
340
            $column = $field->column();
341
            $columns = is_array($column) ? $column : [$column];
342 View Code Duplication
            if ($field instanceof Field\MultipleSelect || $field instanceof Field\Listbox) {
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...
343
                $availInput[$column] = array_filter($availInput[$column], 'strlen');
344
                $availInput[$column] = $availInput[$column] ? : null;
345
            }
346
            /*
347
             *
348
             * For single column field format rules to:
349
             * [
350
             *     'extra.name' => 'required'
351
             *     'extra.email' => 'required'
352
             * ]
353
             *
354
             * For multiple column field with rules like 'required':
355
             * 'extra' => [
356
             *     'start' => 'start_at'
357
             *     'end'   => 'end_at',
358
             * ]
359
             *
360
             * format rules to:
361
             * [
362
             *     'extra.start_atstart' => 'required'
363
             *     'extra.end_atend' => 'required'
364
             * ]
365
             */
366
            $newColumn = array_map(function ($k, $v) use ($rel) {
367
                //Fix ResetInput Function! A Headache Implementation!
368
                return !$k ? "{$rel}.{$v}" : "{$rel}.{$v}:{$k}";
369
            }, array_keys($columns), array_values($columns));
370
371 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...
372
                $newMessages = array_map(function ($v) use ($field, $availInput, $array_key_attach_str) {
373
                    list($k, $c) = explode('.', $v);
374
                    //Fix ResetInput Function! A Headache Implementation!
375
                    $col = explode(':', $c)[0];
376
                    if (array_key_exists($col, $availInput[$k]) && is_array($availInput[$k][$col])) {
377
                        return call_user_func_array('array_merge', array_map(function ($u) use ($v, $field, $array_key_attach_str) {
378
                            return $array_key_attach_str($field->validationMessages, "{$v}:{$u}");
379
                        }, array_keys($availInput[$k][$col])));
380
                    }
381
382
                    //May Have Problem in Dealing with File Upload in Edit Mode
383
                    return $array_key_attach_str($field->validationMessages, $v);
384
                }, $newColumn);
385
                $messages = $array_clean_merge($messages, $newMessages);
386
            }
387
        }
388
389
        return $messages;
390
    }
391
392
    /**
393
     * {@inheritdoc}
394
     */
395
    public function getValidator(array $input)
396
    {
397
        if (!array_key_exists($this->column, $input)) {
398
            return false;
399
        }
400
401
        $rules = $this->getValidationRules($input);
402
        if (empty($rules)) {
403
            return false;
404
        }
405
406 View Code Duplication
        $array_key_clean_undot = function (array $a) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
407
            $keys = preg_grep('/[\.\:]/', array_keys($a));
408
            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...
409
                foreach ($keys as $key) {
410
                    array_set($a, str_replace(':', '', $key), $a[$key]);
411
                    unset($a[$key]);
412
                }
413
            }
414
415
            return $a;
416
        };
417
418 View Code Duplication
        $array_key_clean = function (array $a) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
419
            $a = count($a) ? call_user_func_array('array_merge', array_map(function ($k, $v) {
420
                return [str_replace(':', '', $k) => $v];
421
            }, array_keys($a), array_values($a))) : $a;
422
423
            return $a;
424
        };
425
426
        $attributes = $this->getValidationAttributes($input);
427
        $messages = $this->getValidationMessages($input);
428
        $newInputs = $this->getValidationInput($input);
429
430
        $input = $array_key_clean_undot(array_filter($newInputs, 'strlen', ARRAY_FILTER_USE_KEY));
431
        $rules = $array_key_clean($rules);
432
        $attributes = $array_key_clean($attributes);
433
        $messages = $array_key_clean($messages);
434
435
        if (empty($input)) {
436
            $input = [$rel => $availInput];
0 ignored issues
show
Bug introduced by
The variable $rel does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $availInput does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
437
        }
438
439
        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...
440
    }
441
442
    /**
443
     * Get data for Embedded form.
444
     *
445
     * Normally, data is obtained from the database.
446
     *
447
     * When the data validation errors, data is obtained from session flash.
448
     *
449
     * @return array
450
     */
451
    protected function getEmbeddedData()
452
    {
453
        if ($old = 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...
454
            return $old;
455
        }
456
457
        if (empty($this->value)) {
458
            return [];
459
        }
460
461
        if (is_string($this->value)) {
462
            return json_decode($this->value, true);
463
        }
464
465
        return (array)$this->value;
466
    }
467
468
    /**
469
     * Build a Embedded Form and fill data.
470
     *
471
     * @return EmbeddedForm
472
     */
473
    protected function buildEmbeddedForm()
474
    {
475
        $form = new EmbeddedForm($this->elementName?:$this->column);
0 ignored issues
show
Bug introduced by
It seems like $this->elementName ?: $this->column can also be of type array; however, Encore\Admin\Form\EmbeddedForm::__construct() 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...
476
477
        $form->setParent($this->form);
478
479
        call_user_func($this->builder, $form);
480
481
        if($this->elementName)
482
        {
483
            list($rel,$key,$col)=explode('.',$this->errorKey);
484
            $form->fields()->each(function (Field $field) use ($rel,$key,$col){
485
                $column = $field->column();
486
                $elementName = $elementClass = $errorKey = [];
487
                if (is_array($column)) {
488
                    foreach ($column as $k => $name) {
489
                        $errorKey[$k] = sprintf('%s.%s.%s.%s',$rel,$key,$col,$name);
490
                        $elementName[$k] = sprintf('%s[%s][%s][%s]',$rel,$key,$col,$name);
491
                        $elementClass[$k] = [$rel,$col, $name];
492
                    }
493
                } else {
494
                    $errorKey = sprintf('%s.%s.%s.%s', $rel, $key, $col,$column);
495
                    $elementName = sprintf('%s[%s][%s][%s]', $rel, $key, $col,$column);
496
                    $elementClass = [$rel,$col, $column];
497
                }
498
                $field->setErrorKey($errorKey)
0 ignored issues
show
Bug introduced by
It seems like $errorKey defined by array() on line 486 can also be of type array; however, Encore\Admin\Form\Field::setErrorKey() 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...
499
                    ->setElementName($elementName)
0 ignored issues
show
Bug introduced by
It seems like $elementName defined by $elementClass = $errorKey = array() on line 486 can also be of type array; however, Encore\Admin\Form\Field::setElementName() 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...
500
                    ->setElementClass($elementClass);
501
            });
502
        }
503
        $form->fill($this->getEmbeddedData());
504
505
        return $form;
506
    }
507
508
509
    /**
510
     * Render the form.
511
     *
512
     * @return \Illuminate\View\View
513
     */
514
    public function render()
515
    {
516
        return parent::render()->with(['form' => $this->buildEmbeddedForm()]);
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...
517
    }
518
}
519