Completed
Pull Request — master (#2901)
by
unknown
04:13 queued 01:58
created

Embeds::buildEmbeddedForm()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 12
rs 9.8666
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
use Illuminate\Support\Str;
9
10
class Embeds extends Field
11
{
12
    /**
13
     * @var \Closure
14
     */
15
    protected $builder = null;
16
    protected $view = 'admin::form.embeds';
17
18
    /**
19
     * Create a new HasMany field instance.
20
     *
21
     * @param string $column
22
     * @param array  $arguments
23
     */
24 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...
25
    {
26
        $this->column = $column;
27
28
        if (count($arguments) == 1) {
29
            $this->label = $this->formatLabel();
30
            $this->builder = $arguments[0];
31
        }
32
33
        if (count($arguments) == 2) {
34
            list($this->label, $this->builder) = $arguments;
35
        }
36
    }
37
38
    /**
39
     * Prepare input data for insert or update.
40
     *
41
     * @param array $input
42
     *
43
     * @return array
44
     */
45
    public function prepare($input)
46
    {
47
        $form = $this->buildEmbeddedForm();
48
49
        return $form->setOriginal($this->original)->prepare($input);
50
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55
    public function getValidator(array $input)
56
    {
57
        if (!array_key_exists($this->column, $input)) {
58
            return false;
59
        }
60
61
        $input = array_only($input, $this->column);
62
63
        $rules = $attributes = $messages = [];
64
        $rel = $this->column;
65
66
        $availInput = $input;
67 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...
68
            return call_user_func_array(
69
                'array_merge',
70
                array_map(function ($u, $v) use ($b, $c) {
71
                    return ["{$b}{$c}{$u}" => $v];
72
                }, array_keys($a), array_values($a))
73
            );
74
        };
75
76 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...
77
            $a = count($a) ? call_user_func_array('array_merge', array_map(function ($k, $v) {
78
                return [str_replace(':', '', $k) => $v];
79
            }, array_keys($a), array_values($a))) : $a;
80
81
            return $a;
82
        };
83
84 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...
85
            $keys = preg_grep('/[\.\:]/', array_keys($a));
86
            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...
87
                foreach ($keys as $key) {
88
                    array_set($a, str_replace(':', '', $key), $a[$key]);
89
                    unset($a[$key]);
90
                }
91
            }
92
93
            return $a;
94
        };
95
96
        /** @var Field $field */
97
        foreach ($this->buildEmbeddedForm()->fields() as $field) {
98
            if (!$fieldRules = $field->getRules()) {
99
                continue;
100
            }
101
102
            $column = $field->column();
103
            $columns = is_array($column) ? $column : [$column];
104
            if ($field instanceof Field\MultipleSelect) {
105
                $availInput[$column] = array_filter($availInput[$column], 'strlen');
106
                $availInput[$column] = $availInput[$column] ?: null;
107
            }
108
            /*
109
             *
110
             * For single column field format rules to:
111
             * [
112
             *     'extra.name' => 'required'
113
             *     'extra.email' => 'required'
114
             * ]
115
             *
116
             * For multiple column field with rules like 'required':
117
             * 'extra' => [
118
             *     'start' => 'start_at'
119
             *     'end'   => 'end_at',
120
             * ]
121
             *
122
             * format rules to:
123
             * [
124
             *     'extra.start_atstart' => 'required'
125
             *     'extra.end_atend' => 'required'
126
             * ]
127
             */
128
            $newColumn = array_map(function ($k, $v) use ($rel) {
129
                //Fix ResetInput Function! A Headache Implementation!
130
                return !$k ? "{$rel}.{$v}" : "{$rel}.{$v}:{$k}";
131
            }, array_keys($columns), array_values($columns));
132
133
            $fieldRules = is_array($fieldRules) ? implode('|', $fieldRules) : $fieldRules;
134
            $rules = array_merge($rules, call_user_func_array(
135
                'array_merge',
136
                array_map(function ($v) use ($fieldRules) {
137
                    return [$v => $fieldRules];
138
                }, $newColumn)
139
            ));
140
            $attributes = array_merge($attributes, call_user_func_array(
141
                'array_merge',
142 View Code Duplication
                array_map(function ($v) use ($field) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
143
                    //Fix ResetInput Function! A Headache Implementation!
144
                    $u = $field->label();
145
                    $u .= is_array($field->column()) ? '['.explode(':', explode('.', $v)[1])[0].']' : '';
146
147
                    return [$v => "{$u}"];
148
                }, $newColumn)
149
            ));
150 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...
151
                $newMessages = array_map(function ($v) use ($field, $availInput, $array_key_attach_str) {
152
                    list($rel, $col) = explode('.', $v);
153
                    //Fix ResetInput Function! A Headache Implementation!
154
                    $col1 = explode(':', $col)[0];
155
                    if (!array_key_exists($col1, $availInput[$rel])) {
156
                        return [null => null];
157
                    }
158
                    $rows = $availInput[$rel][$col1];
159
                    if (!is_array($rows)) {
160
                        return $array_key_attach_str($field->validationMessages, $v);
161
                    }
162
                    $r = [];
163
                    foreach (array_keys($rows) as $k) {
164
                        $k = "{$v}{$k}";
165
                        $r = array_merge($r, $array_key_attach_str($field->validationMessages, $k));
166
                    }
167
168
                    return $r;
169
                }, $newColumn);
170
                $newMessages = call_user_func_array('array_merge', $newMessages);
171
                $messages = array_merge($messages, $newMessages);
172
            }
173
        }
174
175
        if (empty($rules)) {
176
            return false;
177
        }
178
        $newInput = call_user_func_array('array_merge', array_map(function ($idx) use ($availInput) {
179
            list($rel, $col) = explode('.', $idx);
180
            //Fix ResetInput Function! A Headache Implementation!
181
            $col1 = explode(':', $col)[0];
182
            if (!array_key_exists($col1, $availInput[$rel])) {
183
                return [null => null];
184
            }
185
            if (is_array($availInput[$rel][$col1])) {
186
                return call_user_func_array('array_merge', array_map(function ($x, $y) use ($idx) {
187
                    return ["{$idx}{$x}" => $y];
188
                }, array_keys($availInput[$rel][$col1]), $availInput[$rel][$col1]));
189
            }
190
191
            return ["{$idx}" => $availInput[$rel][$col1]];
192
        }, array_keys($rules)));
193
194
        $newInput = $array_key_clean_undot($newInput);
195
        $newRules = array_map(function ($idx) use ($availInput, $rules) {
196
            list($rel, $col) = explode('.', $idx);
197
            //Fix ResetInput Function! A Headache Implementation!
198
            $col1 = explode(':', $col)[0];
199
            if (!array_key_exists($col1, $availInput[$rel])) {
200
                return [null => null];
201
            }
202
            if (is_array($availInput[$rel][$col1])) {
203
                return call_user_func_array('array_merge', array_map(function ($x) use ($idx, $rules) {
204
                    return ["{$idx}{$x}" => $rules[$idx]];
205
                }, array_keys($availInput[$rel][$col1])));
206
            }
207
208
            return ["{$idx}" => $rules[$idx]];
209
        }, array_keys($rules));
210
        $newRules = array_filter(call_user_func_array('array_merge', $newRules), 'strlen', ARRAY_FILTER_USE_KEY);
211
        $newRules = $array_key_clean($newRules);
212
213
        $newAttributes = array_map(function ($idx) use ($availInput, $attributes) {
214
            list($rel, $col) = explode('.', $idx);
215
            //Fix ResetInput Function! A Headache Implementation!
216
            $col1 = explode(':', $col)[0];
217
            if (!array_key_exists($col1, $availInput[$rel])) {
218
                return [null => null];
219
            }
220 View Code Duplication
            if (is_array($availInput[$rel][$col1])) {
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...
221
                if (array_keys($availInput[$rel][$col1])) {
222
                    return call_user_func_array('array_merge', array_map(function ($x) use ($idx, $attributes) {
223
                        return ["{$idx}.{$x}" => $attributes[$idx]];
224
                    }, array_keys($availInput[$rel][$col1])));
225
                }
226
227
                return [null => null];
228
            }
229
230
            return ["{$idx}" => $attributes[$idx]];
231
        }, array_keys($attributes));
232
        $newAttributes = array_filter(call_user_func_array('array_merge', $newAttributes), 'strlen');
233
        $newAttributes = $array_key_clean($newAttributes);
234
235
        $messages = $array_key_clean($messages);
236
237
        if (empty($newInput)) {
238
            $newInput = $availInput;
239
        }
240
241
        return Validator::make($newInput, $newRules, $messages, $newAttributes);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return \Illuminate\Suppo...sages, $newAttributes); (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...
242
    }
243
244
    /**
245
     * Format validation attributes.
246
     *
247
     * @param array  $input
248
     * @param string $label
249
     * @param string $column
250
     *
251
     * @return array
252
     */
253 View Code Duplication
    protected function formatValidationAttribute($input, $label, $column)
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...
254
    {
255
        $new = $attributes = [];
256
257
        if (is_array($column)) {
258
            foreach ($column as $index => $col) {
259
                $new[$col.$index] = $col;
260
            }
261
        }
262
263
        foreach (array_keys(array_dot($input)) as $key) {
264
            if (is_string($column)) {
265
                if (Str::endsWith($key, ".$column")) {
266
                    $attributes[$key] = $label;
267
                }
268
            } else {
269
                foreach ($new as $k => $val) {
270
                    if (Str::endsWith($key, ".$k")) {
271
                        $attributes[$key] = $label."[$val]";
272
                    }
273
                }
274
            }
275
        }
276
277
        return $attributes;
278
    }
279
280
    /**
281
     * Reset input key for validation.
282
     *
283
     * @param array $input
284
     * @param array $column $column is the column name array set
285
     *
286
     * @return void.
0 ignored issues
show
Documentation introduced by
The doc-type void. could not be parsed: Unknown type name "void." at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
287
     */
288
    public function resetInputKey(array &$input, array $column)
289
    {
290
        $column = array_flip($column);
291
292 View Code Duplication
        foreach ($input[$this->column] as $key => $value) {
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...
293
            if (!array_key_exists($key, $column)) {
294
                continue;
295
            }
296
297
            $newKey = $key.$column[$key];
298
299
            /*
300
             * set new key
301
             */
302
            array_set($input, "{$this->column}.$newKey", $value);
303
            /*
304
             * forget the old key and value
305
             */
306
            array_forget($input, "{$this->column}.$key");
307
        }
308
    }
309
310
    /**
311
     * Get data for Embedded form.
312
     *
313
     * Normally, data is obtained from the database.
314
     *
315
     * When the data validation errors, data is obtained from session flash.
316
     *
317
     * @return array
318
     */
319
    protected function getEmbeddedData()
320
    {
321
        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...
322
            return $old;
323
        }
324
325
        if (empty($this->value)) {
326
            return [];
327
        }
328
329
        if (is_string($this->value)) {
330
            return json_decode($this->value, true);
331
        }
332
333
        return (array) $this->value;
334
    }
335
336
    /**
337
     * Build a Embedded Form and fill data.
338
     *
339
     * @return EmbeddedForm
340
     */
341
    protected function buildEmbeddedForm()
342
    {
343
        $form = new EmbeddedForm($this->column);
0 ignored issues
show
Bug introduced by
It seems like $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...
344
345
        $form->setParent($this->form);
346
347
        call_user_func($this->builder, $form);
348
349
        $form->fill($this->getEmbeddedData());
350
351
        return $form;
352
    }
353
354
    /**
355
     * Render the form.
356
     *
357
     * @return \Illuminate\View\View
358
     */
359
    public function render()
360
    {
361
        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...
362
    }
363
}
364