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

Embeds::formatValidationAttribute()   B

Complexity

Conditions 8
Paths 9

Size

Total Lines 26

Duplication

Lines 26
Ratio 100 %

Importance

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