Completed
Pull Request — master (#2905)
by
unknown
04:51 queued 02:32
created

Embeds::__construct()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 13

Duplication

Lines 13
Ratio 100 %

Importance

Changes 0
Metric Value
cc 3
nc 4
nop 2
dl 13
loc 13
rs 9.8333
c 0
b 0
f 0
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
    /**
18
     * Create a new HasMany field instance.
19
     *
20
     * @param string $column
21
     * @param array  $arguments
22
     */
23 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...
24
    {
25
        $this->column = $column;
26
27
        if (count($arguments) == 1) {
28
            $this->label = $this->formatLabel();
29
            $this->builder = $arguments[0];
30
        }
31
32
        if (count($arguments) == 2) {
33
            list($this->label, $this->builder) = $arguments;
34
        }
35
    }
36
37
    /**
38
     * Prepare input data for insert or update.
39
     *
40
     * @param array $input
41
     *
42
     * @return array
43
     */
44
    public function prepare($input)
45
    {
46
        $form = $this->buildEmbeddedForm();
47
48
        return $form->setOriginal($this->original)->prepare($input);
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54
    public function getValidationRules(array $input)
55
    {
56
        if (!array_key_exists($this->column, $input)) {
57
            return false;
58
        }
59
60
        $input = array_only($input, $this->column);
61
        $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...
62
        $rel = $this->column;
63
        $availInput = $input;
64 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...
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...
65
            return call_user_func_array(
66
                'array_merge',
67
                array_map(function ($u, $v) use ($b, $c) {
68
                    return ["{$b}{$c}{$u}" => $v];
69
                }, array_keys($a), array_values($a))
70
            );
71
        };
72
73
        $array_clean_merge = function (array $a, $b) {
74
            return $b ? array_merge($a, call_user_func_array('array_merge', $b)) : $a;
75
        };
76
77
        /** @var Field $field */
78
        foreach ($this->buildEmbeddedForm()->fields() as $field) {
79
            if (!$fieldRules = $field->getRules()) {
80
                continue;
81
            }
82
83
            $column = $field->column();
84
            $columns = is_array($column) ? $column : [$column];
85 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...
86
                $availInput[$column] = array_filter($availInput[$column], 'strlen');
87
                $availInput[$column] = $availInput[$column] ?: null;
88
            }
89
            /*
90
             *
91
             * For single column field format rules to:
92
             * [
93
             *     'extra.name' => 'required'
94
             *     'extra.email' => 'required'
95
             * ]
96
             *
97
             * For multiple column field with rules like 'required':
98
             * 'extra' => [
99
             *     'start' => 'start_at'
100
             *     'end'   => 'end_at',
101
             * ]
102
             *
103
             * format rules to:
104
             * [
105
             *     'extra.start_atstart' => 'required'
106
             *     'extra.end_atend' => 'required'
107
             * ]
108
             *
109
             *
110
             * format attributes to:
111
             * [
112
             *      'extra.start_atstart' => "$label[start_at]"
113
             *      'extra.end_atend'     => "$label[end_at]"
114
             * ]
115
             */
116
            $newColumn = array_map(function ($k, $v) use ($rel) {
117
                //Fix ResetInput Function! A Headache Implementation!
118
                return !$k ? "{$rel}.{$v}" : "{$rel}.{$v}:{$k}";
119
            }, array_keys($columns), array_values($columns));
120
121
            $fieldRules = is_array($fieldRules) ? implode('|', $fieldRules) : $fieldRules;
122 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...
123
                list($k, $c) = explode('.', $v);
124
                //Fix ResetInput Function! A Headache Implementation!
125
                $col = explode(':', $c)[0];
126
127
                if (array_key_exists($col, $availInput[$k]) && is_array($availInput[$k][$col])) {
128
                    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...
129
                }
130
131
                //May Have Problem in Dealing with File Upload in Edit Mode
132
                return [$v => $fieldRules];
133
            }, $newColumn);
134
            $rules = $array_clean_merge($rules, $newRules);
135
        }
136
137
        return $rules;
138
    }
139
140
    /**
141
     * {@inheritdoc}
142
     */
143
    public function getValidationAttributes(array $input)
144
    {
145
        if (!array_key_exists($this->column, $input)) {
146
            return false;
147
        }
148
149
        $input = array_only($input, $this->column);
150
        $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...
151
        $rel = $this->column;
152
        $availInput = $input;
153 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...
154
            return call_user_func_array(
155
                'array_merge',
156
                array_map(function ($u, $v) use ($b, $c) {
157
                    return ["{$b}{$c}{$u}" => $v];
158
                }, array_keys($a), array_values($a))
159
            );
160
        };
161
162
        $array_clean_merge = function (array $a, $b) {
163
            return $b ? array_merge($a, call_user_func_array('array_merge', $b)) : $a;
164
        };
165
166
        /** @var Field $field */
167
        foreach ($this->buildEmbeddedForm()->fields() as $field) {
168
            if (!$fieldRules = $field->getRules()) {
169
                continue;
170
            }
171
172
            $column = $field->column();
173
            $columns = is_array($column) ? $column : [$column];
174 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...
175
                $availInput[$column] = array_filter($availInput[$column], 'strlen');
176
                $availInput[$column] = $availInput[$column] ?: null;
177
            }
178
            /*
179
             *
180
             * For single column field format rules to:
181
             * [
182
             *     'extra.name' => 'required'
183
             *     'extra.email' => 'required'
184
             * ]
185
             *
186
             * For multiple column field with rules like 'required':
187
             * 'extra' => [
188
             *     'start' => 'start_at'
189
             *     'end'   => 'end_at',
190
             * ]
191
             *
192
             * format rules to:
193
             * [
194
             *     'extra.start_atstart' => 'required'
195
             *     'extra.end_atend' => 'required'
196
             * ]
197
             *
198
             *
199
             * format attributes to:
200
             * [
201
             *      'extra.start_atstart' => "$label[start_at]"
202
             *      'extra.end_atend'     => "$label[end_at]"
203
             * ]
204
             */
205
            $newColumn = array_map(function ($k, $v) use ($rel) {
206
                //Fix ResetInput Function! A Headache Implementation!
207
                return !$k ? "{$rel}.{$v}" : "{$rel}.{$v}:{$k}";
208
            }, array_keys($columns), array_values($columns));
209
210 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...
211
                list($k, $c) = explode('.', $v);
212
                //Fix ResetInput Function! A Headache Implementation!
213
                $col = explode(':', $c)[0];
214
                if (array_key_exists($col, $availInput[$k]) && is_array($availInput[$k][$col])) {
215
                    return call_user_func_array('array_merge', array_map(function ($u) use ($v, $field) {
216
                        $w = $field->label();
217
                        //Fix ResetInput Function! A Headache Implementation!
218
                        $w .= is_array($field->column()) ? '['.explode(':', explode('.', $v)[2])[0].']' : '';
219
220
                        return ["{$v}:{$u}" => $w];
221
                    }, array_keys($availInput[$k][$col])));
222
                }
223
224
                //May Have Problem in Dealing with File Upload in Edit Mode
225
                $w = $field->label();
226
                //Fix ResetInput Function! A Headache Implementation!
227
                $w .= is_array($field->column()) ? '['.explode(':', explode('.', $v)[2])[0].']' : '';
228
229
                return [$v => $w];
230
            }, $newColumn);
231
            $attributes = $array_clean_merge($attributes, $newAttributes);
232
        }
233
234
        return $attributes;
235
    }
236
237
    /**
238
     * {@inheritdoc}
239
     */
240
    public function getValidationInput(array $input)
241
    {
242
        if (!array_key_exists($this->column, $input)) {
243
            return false;
244
        }
245
246
        $input = array_only($input, $this->column);
247
        $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...
248
        $rel = $this->column;
249
        $availInput = $input;
250 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...
251
            return call_user_func_array(
252
                'array_merge',
253
                array_map(function ($u, $v) use ($b, $c) {
254
                    return ["{$b}{$c}{$u}" => $v];
255
                }, array_keys($a), array_values($a))
256
            );
257
        };
258
259
        $array_clean_merge = function (array $a, $b) {
260
            return $b ? array_merge($a, call_user_func_array('array_merge', $b)) : $a;
261
        };
262
263
        /** @var Field $field */
264
        foreach ($this->buildEmbeddedForm()->fields() as $field) {
265
            if (!$fieldRules = $field->getRules()) {
266
                continue;
267
            }
268
269
            $column = $field->column();
270
            $columns = is_array($column) ? $column : [$column];
271 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...
272
                $availInput[$column] = array_filter($availInput[$column], 'strlen');
273
                $availInput[$column] = $availInput[$column] ?: null;
274
            }
275
            /*
276
             *
277
             * For single column field format rules to:
278
             * [
279
             *     'extra.name' => $value
280
             *     'extra.email' => $value
281
             * ]
282
             *
283
             * For multiple column field with rules like 'required':
284
             * 'extra' => [
285
             *     'start' => 'start_at'
286
             *     'end'   => 'end_at',
287
             * ]
288
             *
289
             * format rules to:
290
             * [
291
             *     'extra.start_atstart' => $value
292
             *     'extra.end_atend' => $value
293
             * ]
294
             */
295
            $newColumn = array_map(function ($k, $v) use ($rel) {
296
                //Fix ResetInput Function! A Headache Implementation!
297
                return !$k ? "{$rel}.{$v}" : "{$rel}.{$v}:{$k}";
298
            }, array_keys($columns), array_values($columns));
299
300 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...
301
                list($k, $c) = explode('.', $v);
302
                //Fix ResetInput Function! A Headache Implementation!
303
                $col = explode(':', $c)[0];
304
                if (!array_key_exists($col, $availInput[$k])) {
305
                    return [$v => null];
306
                }
307
308
                if (array_key_exists($col, $availInput[$k]) && is_array($availInput[$k][$col])) {
309
                    return $array_key_attach_str($availInput[$k][$col], $v, ':');
310
                }
311
312
                return [$v => $availInput[$k][$col]];
313
            }, $newColumn);
314
            $newInputs = $array_clean_merge($newInputs, $newInput);
315
        }
316
317
        return $newInputs;
318
    }
319
320
    /**
321
     * {@inheritdoc}
322
     */
323
    public function getValidationMessages(array $input)
324
    {
325
        if (!array_key_exists($this->column, $input)) {
326
            return false;
327
        }
328
329
        $input = array_only($input, $this->column);
330
        $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...
331
        $rel = $this->column;
332
        $availInput = $input;
333 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...
334
            return call_user_func_array(
335
                'array_merge',
336
                array_map(function ($u, $v) use ($b, $c) {
337
                    return ["{$b}{$c}{$u}" => $v];
338
                }, array_keys($a), array_values($a))
339
            );
340
        };
341
342
        $array_clean_merge = function (array $a, $b) {
343
            return $b ? array_merge($a, call_user_func_array('array_merge', $b)) : $a;
344
        };
345
346
        /** @var Field $field */
347
        foreach ($this->buildEmbeddedForm()->fields() as $field) {
348
            if (!$fieldRules = $field->getRules()) {
349
                continue;
350
            }
351
352
            $column = $field->column();
353
            $columns = is_array($column) ? $column : [$column];
354 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...
355
                $availInput[$column] = array_filter($availInput[$column], 'strlen');
356
                $availInput[$column] = $availInput[$column] ?: null;
357
            }
358
359
            $newColumn = array_map(function ($k, $v) use ($rel) {
360
                //Fix ResetInput Function! A Headache Implementation!
361
                return !$k ? "{$rel}.{$v}" : "{$rel}.{$v}:{$k}";
362
            }, array_keys($columns), array_values($columns));
363
364 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...
365
                $newMessages = array_map(function ($v) use ($field, $availInput, $array_key_attach_str) {
366
                    list($k, $c) = explode('.', $v);
367
                    //Fix ResetInput Function! A Headache Implementation!
368
                    $col = explode(':', $c)[0];
369
                    if (array_key_exists($col, $availInput[$k]) && is_array($availInput[$k][$col])) {
370
                        return call_user_func_array('array_merge', array_map(function ($u) use ($v, $field, $array_key_attach_str) {
371
                            return $array_key_attach_str($field->validationMessages, "{$v}:{$u}");
372
                        }, array_keys($availInput[$k][$col])));
373
                    }
374
375
                    //May Have Problem in Dealing with File Upload in Edit Mode
376
                    return $array_key_attach_str($field->validationMessages, $v);
377
                }, $newColumn);
378
                $messages = $array_clean_merge($messages, $newMessages);
379
            }
380
        }
381
382
        return $messages;
383
    }
384
385
    /**
386
     * {@inheritdoc}
387
     */
388
    public function getValidator(array $input)
389
    {
390
        if (!array_key_exists($this->column, $input)) {
391
            return false;
392
        }
393
394
        $rules = $this->getValidationRules($input);
395
        if (empty($rules)) {
396
            return false;
397
        }
398
399 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...
400
            $keys = preg_grep('/[\.\:]/', array_keys($a));
401
            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...
402
                foreach ($keys as $key) {
403
                    array_set($a, str_replace(':', '', $key), $a[$key]);
404
                    unset($a[$key]);
405
                }
406
            }
407
408
            return $a;
409
        };
410
411 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...
412
            $a = count($a) ? call_user_func_array('array_merge', array_map(function ($k, $v) {
413
                return [str_replace(':', '', $k) => $v];
414
            }, array_keys($a), array_values($a))) : $a;
415
416
            return $a;
417
        };
418
419
        $attributes = $this->getValidationAttributes($input);
420
        $messages = $this->getValidationMessages($input);
421
        $newInputs = $this->getValidationInput($input);
422
423
        $input = $array_key_clean_undot(array_filter($newInputs, 'strlen', ARRAY_FILTER_USE_KEY));
424
        $rules = $array_key_clean($rules);
425
        $attributes = $array_key_clean($attributes);
426
        $messages = $array_key_clean($messages);
427
428
        if (empty($input)) {
429
            $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...
430
        }
431
432
        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...
433
    }
434
435
    /**
436
     * Get data for Embedded form.
437
     *
438
     * Normally, data is obtained from the database.
439
     *
440
     * When the data validation errors, data is obtained from session flash.
441
     *
442
     * @return array
443
     */
444
    protected function getEmbeddedData()
445
    {
446
        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...
447
            return $old;
448
        }
449
450
        if (empty($this->value)) {
451
            return [];
452
        }
453
454
        if (is_string($this->value)) {
455
            return json_decode($this->value, true);
456
        }
457
458
        return (array) $this->value;
459
    }
460
461
    /**
462
     * Build a Embedded Form and fill data.
463
     *
464
     * @return EmbeddedForm
465
     */
466
    protected function buildEmbeddedForm()
467
    {
468
        $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...
469
470
        $form->setParent($this->form);
471
472
        call_user_func($this->builder, $form);
473
474
        //Fix the Bug of Embeds Fields Cannot be used within HasMany
475
        if ($this->elementName) {
476
            list($rel, $key, $col) = explode('.', $this->errorKey);
477
            $form->fields()->each(function (Field $field) use ($rel,$key,$col) {
478
                $column = $field->column();
479
                $elementName = $elementClass = $errorKey = [];
480
                if (is_array($column)) {
481
                    foreach ($column as $k => $name) {
482
                        $errorKey[$k] = sprintf('%s.%s.%s.%s', $rel, $key, $col, $name);
483
                        $elementName[$k] = sprintf('%s[%s][%s][%s]', $rel, $key, $col, $name);
484
                        $elementClass[$k] = [$rel, $col, $name];
485
                    }
486
                } else {
487
                    $errorKey = sprintf('%s.%s.%s.%s', $rel, $key, $col, $column);
488
                    $elementName = sprintf('%s[%s][%s][%s]', $rel, $key, $col, $column);
489
                    $elementClass = [$rel, $col, $column];
490
                }
491
                $field->setErrorKey($errorKey)
0 ignored issues
show
Bug introduced by
It seems like $errorKey defined by array() on line 479 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...
492
                    ->setElementName($elementName)
0 ignored issues
show
Bug introduced by
It seems like $elementName defined by $elementClass = $errorKey = array() on line 479 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...
493
                    ->setElementClass($elementClass);
494
            });
495
        }
496
        $form->fill($this->getEmbeddedData());
497
498
        return $form;
499
    }
500
501
    /**
502
     * Render the form.
503
     *
504
     * @return \Illuminate\View\View
505
     */
506
    public function render()
507
    {
508
        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...
509
    }
510
}
511