Completed
Pull Request — master (#3073)
by
unknown
02:49
created

Embeds::getValidationMessages()   C

Complexity

Conditions 16
Paths 15

Size

Total Lines 62

Duplication

Lines 33
Ratio 53.23 %

Importance

Changes 0
Metric Value
cc 16
nc 15
nop 1
dl 33
loc 62
rs 5.5666
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
use Illuminate\Support\Str;
9
10 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...
11
    function array_key_attach_str(array $a, string $b, string $c = '.')
12
    {
13
        return call_user_func_array(
14
            'array_merge',
15
            array_map(function ($u, $v) use ($b, $c) {
16
                return ["{$b}{$c}{$u}" => $v];
17
            }, array_keys($a), array_values($a))
18
        );
19
    };
20
}
21
22 View Code Duplication
if (!function_exists('Encore\Admin\Form\Field\array_clean_merge')) {
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...
23
    function array_clean_merge(array $a, $b)
24
    {
25
        return $b ? array_merge($a, call_user_func_array('array_merge', $b)) : $a;
26
    };
27
}
28
29 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...
30
    function array_key_clean_undot(array $a)
31
    {
32
        $keys = preg_grep('/[\.\:]/', array_keys($a));
33
        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...
34
            foreach ($keys as $key) {
35
                array_set($a, str_replace(':', '', $key), $a[$key]);
36
                unset($a[$key]);
37
            }
38
        }
39
40
        return $a;
41
    };
42
}
43
44 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...
45
    function array_key_clean(array $a)
46
    {
47
        $a = count($a) ? call_user_func_array('array_merge', array_map(function ($k, $v) {
48
            return [str_replace(':', '', $k) => $v];
49
        }, array_keys($a), array_values($a))) : $a;
50
51
        return $a;
52
    };
53
}
54
55
class Embeds extends Field
56
{
57
    /**
58
     * @var \Closure
59
     */
60
    protected $builder = null;
61
62
    /**
63
     * Create a new HasMany field instance.
64
     *
65
     * @param string $column
66
     * @param array  $arguments
67
     */
68 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...
69
    {
70
        $this->column = $column;
71
72
        if (count($arguments) == 1) {
73
            $this->label = $this->formatLabel();
74
            $this->builder = $arguments[0];
75
        }
76
77
        if (count($arguments) == 2) {
78
            list($this->label, $this->builder) = $arguments;
79
        }
80
    }
81
82
    /**
83
     * Prepare input data for insert or update.
84
     *
85
     * @param array $input
86
     *
87
     * @return array
88
     */
89
    public function prepare($input)
90
    {
91
        $form = $this->buildEmbeddedForm();
92
93
        return $form->setOriginal($this->original)->prepare($input);
94
    }
95
96
    /**
97
     * Prepare validation rules based on input data.
98
     *
99
     * @param array $input
100
     *
101
     * @return array
102
     */
103
    public function getValidationRules(array $input)
104
    {
105
        if (!array_key_exists($this->column, $input)) {
106
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by Encore\Admin\Form\Field\Embeds::getValidationRules of type array.

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...
107
        }
108
109
        $input = array_only($input, $this->column);
110
        $rules = [];
111
        $rel = $this->column;
112
        $availInput = $input;
113
114
        /** @var Field $field */
115
        foreach ($this->buildEmbeddedForm()->fields() as $field) {
116
            if (!$fieldRules = $field->getRules()) {
117
                continue;
118
            }
119
120
            $column = $field->column();
121
            $columns = is_array($column) ? $column : [$column];
122 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...
123
                $field instanceof Field\MultipleSelect
124
                || $field instanceof Field\Listbox
125
                || $field instanceof Field\Checkbox
126
                || $field instanceof Field\Tags
127
                || $field instanceof Field\MultipleImage
128
                || $field instanceof Field\MultipleFile
129
            ) {
130
                $availInput[$column] = array_filter($availInput[$column], 'strlen');
131
                $availInput[$column] = $availInput[$column] ?: null;
132
            }
133
            /*
134
             *
135
             * For single column field format rules to:
136
             * [
137
             *     'extra.name' => 'required'
138
             *     'extra.email' => 'required'
139
             * ]
140
             *
141
             * For multiple column field with rules like 'required':
142
             * 'extra' => [
143
             *     'start' => 'start_at'
144
             *     'end'   => 'end_at',
145
             * ]
146
             *
147
             * format rules to:
148
             * [
149
             *     'extra.start_atstart' => 'required'
150
             *     'extra.end_atend' => 'required'
151
             * ]
152
             *
153
             *
154
             * format attributes to:
155
             * [
156
             *      'extra.start_atstart' => "$label[start_at]"
157
             *      'extra.end_atend'     => "$label[end_at]"
158
             * ]
159
             */
160
            $newColumn = array_map(function ($k, $v) use ($rel) {
161
                //Fix ResetInput Function! A Headache Implementation!
162
                return !$k ? "{$rel}.{$v}" : "{$rel}.{$v}:{$k}";
163
            }, array_keys($columns), array_values($columns));
164
165
            $fieldRules = is_array($fieldRules) ? implode('|', $fieldRules) : $fieldRules;
166 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...
167
                list($k, $c) = explode('.', $v);
168
                //Fix ResetInput Function! A Headache Implementation!
169
                $col = explode(':', $c)[0];
170
171
                if (array_key_exists($col, $availInput[$k]) && is_array($availInput[$k][$col])) {
172
                    return array_key_attach_str(preg_replace('/./', $fieldRules, $availInput[$k][$col]), $v, ':');
173
                }
174
175
                //May Have Problem in Dealing with File Upload in Edit Mode
176
                return [$v => $fieldRules];
177
            }, $newColumn);
178
            $rules = array_clean_merge($rules, $newRules);
179
        }
180
181
        return $rules;
182
    }
183
184
    /**
185
     * Prepare validation attributes based on input data.
186
     *
187
     * @param array $input
188
     *
189
     * @return array
190
     */
191
    public function getValidationAttributes(array $input)
192
    {
193
        if (!array_key_exists($this->column, $input)) {
194
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by Encore\Admin\Form\Field\...getValidationAttributes of type array.

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...
195
        }
196
197
        $input = array_only($input, $this->column);
198
        $attributes = [];
199
        $rel = $this->column;
200
        $availInput = $input;
201
        /** @var Field $field */
202
        foreach ($this->buildEmbeddedForm()->fields() as $field) {
203
            if (!$field->getRules()) {
204
                continue;
205
            }
206
207
            $column = $field->column();
208
            $columns = is_array($column) ? $column : [$column];
209 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...
210
                $field instanceof Field\MultipleSelect
211
                || $field instanceof Field\Listbox
212
                || $field instanceof Field\Checkbox
213
                || $field instanceof Field\Tags
214
                || $field instanceof Field\MultipleImage
215
                || $field instanceof Field\MultipleFile
216
            ) {
217
                $availInput[$column] = array_filter($availInput[$column], 'strlen');
218
                $availInput[$column] = $availInput[$column] ?: null;
219
            }
220
            /*
221
             *
222
             * For single column field format rules to:
223
             * [
224
             *     'extra.name' => 'required'
225
             *     'extra.email' => 'required'
226
             * ]
227
             *
228
             * For multiple column field with rules like 'required':
229
             * 'extra' => [
230
             *     'start' => 'start_at'
231
             *     'end'   => 'end_at',
232
             * ]
233
             *
234
             * format rules to:
235
             * [
236
             *     'extra.start_atstart' => 'required'
237
             *     'extra.end_atend' => 'required'
238
             * ]
239
             *
240
             *
241
             * format attributes to:
242
             * [
243
             *      'extra.start_atstart' => "$label[start_at]"
244
             *      'extra.end_atend'     => "$label[end_at]"
245
             * ]
246
             */
247
            $newColumn = array_map(function ($k, $v) use ($rel) {
248
                //Fix ResetInput Function! A Headache Implementation!
249
                return !$k ? "{$rel}.{$v}" : "{$rel}.{$v}:{$k}";
250
            }, array_keys($columns), array_values($columns));
251
252 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...
253
                list($k, $c) = explode('.', $v);
254
                //Fix ResetInput Function! A Headache Implementation!
255
                $col = explode(':', $c)[0];
256
                if (array_key_exists($col, $availInput[$k]) && is_array($availInput[$k][$col])) {
257
                    return call_user_func_array('array_merge', array_map(function ($u) use ($v, $field) {
258
                        $w = $field->label();
259
                        //Fix ResetInput Function! A Headache Implementation!
260
                        $w .= is_array($field->column()) ? '[' . explode(':', explode('.', $v)[2])[0] . ']' : '';
261
262
                        return ["{$v}:{$u}" => $w];
263
                    }, array_keys($availInput[$k][$col])));
264
                }
265
266
                //May Have Problem in Dealing with File Upload in Edit Mode
267
                $w = $field->label();
268
                //Fix ResetInput Function! A Headache Implementation!
269
                $w .= is_array($field->column()) ? '[' . explode(':', explode('.', $v)[2])[0] . ']' : '';
270
271
                return [$v => $w];
272
            }, $newColumn);
273
            $attributes = array_clean_merge($attributes, $newAttributes);
274
        }
275
276
        return $attributes;
277
    }
278
279
    /**
280
     * Prepare input data for insert or update.
281
     *
282
     * @param array $input
283
     *
284
     * @return array
285
     */
286
    public function getValidationInput(array $input)
287
    {
288
        if (!array_key_exists($this->column, $input)) {
289
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by Encore\Admin\Form\Field\Embeds::getValidationInput of type array.

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...
290
        }
291
292
        $input = array_only($input, $this->column);
293
        $newInputs = [];
294
        $rel = $this->column;
295
        $availInput = $input;
296
297
        /** @var Field $field */
298
        foreach ($this->buildEmbeddedForm()->fields() as $field) {
299
            if (!$field->getRules()) {
300
                continue;
301
            }
302
303
            $column = $field->column();
304
            $columns = is_array($column) ? $column : [$column];
305 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...
306
                $field instanceof Field\MultipleSelect
307
                || $field instanceof Field\Listbox
308
                || $field instanceof Field\Checkbox
309
                || $field instanceof Field\Tags
310
                || $field instanceof Field\MultipleImage
311
                || $field instanceof Field\MultipleFile
312
            ) {
313
                $availInput[$column] = array_filter($availInput[$column], 'strlen');
314
                $availInput[$column] = $availInput[$column] ?: null;
315
            }
316
            /*
317
             *
318
             * For single column field format rules to:
319
             * [
320
             *     'extra.name' => $value
321
             *     'extra.email' => $value
322
             * ]
323
             *
324
             * For multiple column field with rules like 'required':
325
             * 'extra' => [
326
             *     'start' => 'start_at'
327
             *     'end'   => 'end_at',
328
             * ]
329
             *
330
             * format rules to:
331
             * [
332
             *     'extra.start_atstart' => $value
333
             *     'extra.end_atend' => $value
334
             * ]
335
             */
336
            $newColumn = array_map(function ($k, $v) use ($rel) {
337
                //Fix ResetInput Function! A Headache Implementation!
338
                return !$k ? "{$rel}.{$v}" : "{$rel}.{$v}:{$k}";
339
            }, array_keys($columns), array_values($columns));
340
341 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...
342
                list($k, $c) = explode('.', $v);
343
                //Fix ResetInput Function! A Headache Implementation!
344
                $col = explode(':', $c)[0];
345
                if (!array_key_exists($col, $availInput[$k])) {
346
                    return [$v => null];
347
                }
348
349
                if (array_key_exists($col, $availInput[$k]) && is_array($availInput[$k][$col])) {
350
                    return array_key_attach_str($availInput[$k][$col], $v, ':');
351
                }
352
353
                return [$v => $availInput[$k][$col]];
354
            }, $newColumn);
355
            $newInputs = array_clean_merge($newInputs, $newInput);
356
        }
357
358
        return $newInputs;
359
    }
360
361
    /**
362
     * Prepare customer validation messages based on input data.
363
     *
364
     * @param array $input
365
     *
366
     * @return array
367
     */
368
    public function getValidationMessages(array $input)
369
    {
370
        if (!array_key_exists($this->column, $input)) {
371
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by Encore\Admin\Form\Field\...::getValidationMessages of type array.

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...
372
        }
373
374
        $input = array_only($input, $this->column);
375
        $messages = [];
376
        $rel = $this->column;
377
        $availInput = $input;
378
379
        /** @var Field $field */
380
        foreach ($this->buildEmbeddedForm()->fields() as $field) {
381
            if (!$field->getRules()) {
382
                continue;
383
            }
384
385
            $column = $field->column();
386
            $columns = is_array($column) ? $column : [$column];
387 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...
388
                $field instanceof Field\MultipleSelect
389
                || $field instanceof Field\Listbox
390
                || $field instanceof Field\Checkbox
391
                || $field instanceof Field\Tags
392
                || $field instanceof Field\MultipleImage
393
                || $field instanceof Field\MultipleFile
394
            ) {
395
                $availInput[$column] = array_filter($availInput[$column], 'strlen');
396
                $availInput[$column] = $availInput[$column] ?: null;
397
            }
398
399
            $newColumn = array_map(function ($k, $v) use ($rel) {
400
                //Fix ResetInput Function! A Headache Implementation!
401
                return !$k ? "{$rel}.{$v}" : "{$rel}.{$v}:{$k}";
402
            }, array_keys($columns), array_values($columns));
403
404 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...
405
                $newMessages = array_map(function ($v) use ($field, $availInput) {
406
                    list($k, $c) = explode('.', $v);
407
                    //Fix ResetInput Function! A Headache Implementation!
408
                    $col = explode(':', $c)[0];
409
                    if (array_key_exists($col, $availInput[$k]) && is_array($availInput[$k][$col])) {
410
                        return call_user_func_array(
411
                            'array_merge',
412
                            array_map(function ($u) use (
413
                                $v,
414
                                $field
415
                            ) {
416
                                return array_key_attach_str($field->validationMessages, "{$v}:{$u}");
417
                            }, array_keys($availInput[$k][$col]))
418
                        );
419
                    }
420
421
                    //May Have Problem in Dealing with File Upload in Edit Mode
422
                    return array_key_attach_str($field->validationMessages, $v);
423
                }, $newColumn);
424
                $messages = array_clean_merge($messages, $newMessages);
425
            }
426
        }
427
428
        return $messages;
429
    }
430
431
    /**
432
     * {@inheritdoc}
433
     */
434
    public function getValidator(array $input)
435
    {
436
        if (!array_key_exists($this->column, $input)) {
437
            return false;
438
        }
439
440
        $rules = $this->getValidationRules($input);
441
        if (empty($rules)) {
442
            return false;
443
        }
444
445
        $attributes = $this->getValidationAttributes($input);
446
        $messages = $this->getValidationMessages($input);
447
        $newInputs = $this->getValidationInput($input);
448
449
        $input = array_key_clean_undot(array_filter($newInputs, 'strlen', ARRAY_FILTER_USE_KEY));
450
        $rules = array_key_clean($rules);
451
        $attributes = array_key_clean($attributes);
452
        $messages = array_key_clean($messages);
453
454
        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...
455
    }
456
457
    /**
458
     * Get data for Embedded form.
459
     *
460
     * Normally, data is obtained from the database.
461
     *
462
     * When the data validation errors, data is obtained from session flash.
463
     *
464
     * @return array
465
     */
466
    protected function getEmbeddedData()
467
    {
468
        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...
469
            return $old;
470
        }
471
472
        if (empty($this->value)) {
473
            return [];
474
        }
475
476
        if (is_string($this->value)) {
477
            return json_decode($this->value, true);
478
        }
479
480
        return (array)$this->value;
481
    }
482
483
    /**
484
     * Build a Embedded Form and fill data.
485
     *
486
     * @return EmbeddedForm
487
     */
488
    protected function buildEmbeddedForm()
489
    {
490
        $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...
491
492
        $form->setParent($this->form);
493
494
        call_user_func($this->builder, $form);
495
496
        //Fix the Bug of Embeds Fields Cannot be used within HasMany
497
        if ($this->elementName) {
498
            list($rel, $key, $col) = explode('.', $this->errorKey);
499
            $form->fields()->each(function (Field $field) use ($rel, $key, $col) {
500
                $column = $field->column();
501
                $elementName = $elementClass = $errorKey = [];
502
                if (is_array($column)) {
503
                    foreach ($column as $k => $name) {
504
                        $errorKey[$k] = sprintf('%s.%s.%s.%s', $rel, $key, $col, $name);
505
                        $elementName[$k] = sprintf('%s[%s][%s][%s]', $rel, $key, $col, $name);
506
                        $elementClass[$k] = [$rel, $col, $name];
507
                    }
508
                } else {
509
                    $errorKey = sprintf('%s.%s.%s.%s', $rel, $key, $col, $column);
510
                    $elementName = sprintf('%s[%s][%s][%s]', $rel, $key, $col, $column);
511
                    $elementClass = [$rel, $col, $column];
512
                }
513
                $field->setErrorKey($errorKey)
0 ignored issues
show
Bug introduced by
It seems like $errorKey defined by array() on line 501 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...
514
                    ->setElementName($elementName)
0 ignored issues
show
Bug introduced by
It seems like $elementName defined by $elementClass = $errorKey = array() on line 501 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...
515
                    ->setElementClass($elementClass);
516
            });
517
        }
518
        $form->fill($this->getEmbeddedData());
519
520
        return $form;
521
    }
522
523
    /**
524
     * Render the form.
525
     *
526
     * @return \Illuminate\View\View
527
     */
528
    public function render()
529
    {
530
        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...
531
    }
532
}
533