Completed
Pull Request — master (#2901)
by
unknown
02:20
created

Embeds::__construct()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 13

Duplication

Lines 13
Ratio 100 %

Importance

Changes 0
Metric Value
cc 3
nc 4
nop 2
dl 13
loc 13
rs 9.8333
c 0
b 0
f 0
1
<?php
2
3
namespace Encore\Admin\Form\Field;
4
5
use Encore\Admin\Form\EmbeddedForm;
6
use Encore\Admin\Form\Field;
7
use Illuminate\Support\Facades\Validator;
8
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
     * Create a new HasMany field instance.
19
     *
20
     * @param string $column
21
     * @param array  $arguments
22
     */
23 View Code Duplication
    public function __construct($column, $arguments = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
24
    {
25
        $this->column = $column;
26
27
        if (count($arguments) == 1) {
28
            $this->label = $this->formatLabel();
29
            $this->builder = $arguments[0];
30
        }
31
32
        if (count($arguments) == 2) {
33
            list($this->label, $this->builder) = $arguments;
34
        }
35
    }
36
37
    /**
38
     * Prepare input data for insert or update.
39
     *
40
     * @param array $input
41
     *
42
     * @return array
43
     */
44
    public function prepare($input)
45
    {
46
        $form = $this->buildEmbeddedForm();
47
48
        return $form->setOriginal($this->original)->prepare($input);
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54
    public function getValidator(array $input)
55
    {
56
        if (!array_key_exists($this->column, $input)) {
57
            return false;
58
        }
59
60
        $input = array_only($input, $this->column);
61
62
        $rules = $attributes = $messages = [];
63
        $rel = $this->column;
64
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
            return $a;
81
        };
82
83 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...
84
            if (count($a))
85
                foreach ($a as $key => $val) {
86
                array_set($a, str_replace(':', '', $key), $val);
87
                if (preg_match('/[\.\:]/', $key)) {
88
                    unset($a[$key]);
89
                }
90
            }
91
            return $a;
92
        };
93
94
        /** @var Field $field */
95
        foreach ($this->buildEmbeddedForm()->fields() as $field) {
96
            if (!$fieldRules = $field->getRules()) {
97
                continue;
98
            }
99
100
            $column = $field->column();
101
            $columns = is_array($column) ? $column : [$column];
102
            if ($field instanceof Field\MultipleSelect) {
103
                $availInput[$column] = array_filter($availInput[$column], 'strlen');
104
                $availInput[$column] = $availInput[$column] ? : null;
105
            }
106
            /*
107
             *
108
             * For single column field format rules to:
109
             * [
110
             *     'extra.name' => 'required'
111
             *     'extra.email' => 'required'
112
             * ]
113
             *
114
             * For multiple column field with rules like 'required':
115
             * 'extra' => [
116
             *     'start' => 'start_at'
117
             *     'end'   => 'end_at',
118
             * ]
119
             *
120
             * format rules to:
121
             * [
122
             *     'extra.start_atstart' => 'required'
123
             *     'extra.end_atend' => 'required'
124
             * ]
125
             */
126
            $newColumn = array_map(function ($k, $v) use ($rel) {
127
                //Fix ResetInput Function! A Headache Implementation!
128
                return !$k ? "{$rel}.{$v}" : "{$rel}.{$v}:{$k}";
129
            }, array_keys($columns), array_values($columns));
130
131
            $fieldRules = is_array($fieldRules) ? implode('|', $fieldRules) : $fieldRules;
132
            $rules = array_merge($rules, call_user_func_array(
133
                'array_merge',
134
                array_map(function ($v) use ($fieldRules) {
135
                    return [$v => $fieldRules];
136
                }, $newColumn)
137
            ));
138
            $attributes = array_merge($attributes, call_user_func_array(
139
                'array_merge',
140 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...
141
                    //Fix ResetInput Function! A Headache Implementation!
142
                    $u = $field->label();
143
                    $u .= is_array($field->column()) ? '[' . explode(':', explode('.', $v)[1])[0] . ']' : '';
144
                    return [$v => "{$u}"];
145
                }, $newColumn)
146
            ));
147 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...
148
149
                $newMessages = array_map(function ($v) use ($field, $availInput, $array_key_attach_str) {
150
                    list($rel, $col) = explode('.', $v);
151
                    //Fix ResetInput Function! A Headache Implementation!
152
                    $col1 = explode(':', $col)[0];
153
                    if (!array_key_exists($col1, $availInput[$rel])) return [null => null];
154
                    $rows = $availInput[$rel][$col1];
155
                    if (!is_array($rows))
156
                        return $array_key_attach_str($field->validationMessages, $v);
157
                    $r = [];
158
                    foreach (array_keys($rows) as $k) {
159
                        $k = "{$v}{$k}";
160
                        $r = array_merge($r, $array_key_attach_str($field->validationMessages, $k));
161
                    }
162
                    return $r;
163
                }, $newColumn);
164
                $newMessages = call_user_func_array('array_merge', $newMessages);
165
                $messages = array_merge($messages, $newMessages);
166
            }
167
        }
168
169
        if (empty($rules)) {
170
            return false;
171
        }
172
        $newInput = call_user_func_array('array_merge', array_map(function ($idx) use ($availInput) {
173
            list($rel, $col) = explode('.', $idx);
174
            //Fix ResetInput Function! A Headache Implementation!
175
            $col1 = explode(':', $col)[0];
176
            if (!array_key_exists($col1, $availInput[$rel])) return [null => null];
177
            if (is_array($availInput[$rel][$col1])) {
178
                return call_user_func_array('array_merge', array_map(function ($x, $y) use ($idx) {
179
                    return ["{$idx}{$x}" => $y];
180
                }, array_keys($availInput[$rel][$col1]), $availInput[$rel][$col1]));
181
            }
182
            return ["{$idx}" => $availInput[$rel][$col1]];
183
        }, array_keys($rules)));
184
185
        $newInput = $array_key_clean_undot($newInput);
186
        $newRules = array_map(function ($idx) use ($availInput, $rules) {
187
            list($rel, $col) = explode('.', $idx);
188
            //Fix ResetInput Function! A Headache Implementation!
189
            $col1 = explode(':', $col)[0];
190
            if (!array_key_exists($col1, $availInput[$rel])) return [null => null];
191
            if (is_array($availInput[$rel][$col1])) {
192
                return call_user_func_array('array_merge', array_map(function ($x) use ($idx, $rules) {
193
                    return ["{$idx}{$x}" => $rules[$idx]];
194
                }, array_keys($availInput[$rel][$col1])));
195
            }
196
            return ["{$idx}" => $rules[$idx]];
197
198
        }, array_keys($rules));
199
        $newRules = array_filter(call_user_func_array('array_merge', $newRules), 'strlen', ARRAY_FILTER_USE_KEY);
200
        $newRules = $array_key_clean($newRules);;
201
202
        $newAttributes = array_map(function ($idx) use ($availInput, $attributes) {
203
            list($rel, $col) = explode('.', $idx);
204
            //Fix ResetInput Function! A Headache Implementation!
205
            $col1 = explode(':', $col)[0];
206
            if (!array_key_exists($col1, $availInput[$rel])) return [null => null];
207 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...
208
                if (array_keys($availInput[$rel][$col1]))
209
                    return call_user_func_array('array_merge', array_map(function ($x) use ($idx, $attributes) {
210
                    return ["{$idx}.{$x}" => $attributes[$idx]];
211
                }, array_keys($availInput[$rel][$col1])));
212
                return [null => null];
213
            }
214
215
            return ["{$idx}" => $attributes[$idx]];
216
        }, array_keys($attributes));
217
        $newAttributes = array_filter(call_user_func_array('array_merge', $newAttributes), 'strlen');
218
        $newAttributes = $array_key_clean($newAttributes);
219
220
        $messages = $array_key_clean($messages);
221
222
        if (empty($newInput)) {
223
            $newInput = $availInput;
224
        }
225
        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...
226
    }
227
228
229
230
    /**
231
     * Format validation attributes.
232
     *
233
     * @param array  $input
234
     * @param string $label
235
     * @param string $column
236
     *
237
     * @return array
238
     */
239 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...
240
    {
241
        $new = $attributes = [];
242
243
        if (is_array($column)) {
244
            foreach ($column as $index => $col) {
245
                $new[$col . $index] = $col;
246
            }
247
        }
248
249
        foreach (array_keys(array_dot($input)) as $key) {
250
            if (is_string($column)) {
251
                if (Str::endsWith($key, ".$column")) {
252
                    $attributes[$key] = $label;
253
                }
254
            } else {
255
                foreach ($new as $k => $val) {
256
                    if (Str::endsWith($key, ".$k")) {
257
                        $attributes[$key] = $label . "[$val]";
258
                    }
259
                }
260
            }
261
        }
262
263
        return $attributes;
264
    }
265
266
    /**
267
     * Reset input key for validation.
268
     *
269
     * @param array $input
270
     * @param array $column $column is the column name array set
271
     *
272
     * @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...
273
     */
274
    public function resetInputKey(array &$input, array $column)
275
    {
276
        $column = array_flip($column);
277
278 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...
279
            if (!array_key_exists($key, $column)) {
280
                continue;
281
            }
282
283
            $newKey = $key . $column[$key];
284
285
            /*
286
             * set new key
287
             */
288
            array_set($input, "{$this->column}.$newKey", $value);
289
            /*
290
             * forget the old key and value
291
             */
292
            array_forget($input, "{$this->column}.$key");
293
        }
294
    }
295
296
    /**
297
     * Get data for Embedded form.
298
     *
299
     * Normally, data is obtained from the database.
300
     *
301
     * When the data validation errors, data is obtained from session flash.
302
     *
303
     * @return array
304
     */
305
    protected function getEmbeddedData()
306
    {
307
        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...
308
            return $old;
309
        }
310
311
        if (empty($this->value)) {
312
            return [];
313
        }
314
315
        if (is_string($this->value)) {
316
            return json_decode($this->value, true);
317
        }
318
319
        return (array)$this->value;
320
    }
321
322
    /**
323
     * Build a Embedded Form and fill data.
324
     *
325
     * @return EmbeddedForm
326
     */
327
    protected function buildEmbeddedForm()
328
    {
329
        $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...
330
331
        $form->setParent($this->form);
332
333
        call_user_func($this->builder, $form);
334
335
        $form->fill($this->getEmbeddedData());
336
337
        return $form;
338
    }
339
340
    /**
341
     * Render the form.
342
     *
343
     * @return \Illuminate\View\View
344
     */
345
    public function render()
346
    {
347
        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...
348
    }
349
}
350