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

Embeds::getEmbeddedData()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 4
nop 0
dl 0
loc 16
rs 9.7333
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
        $rules = $attributes = $messages = $newInputs = [];
63
        $rel = $this->column;
64
        $availInput = $input;
65 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...
66
            return call_user_func_array(
67
                'array_merge',
68
                array_map(function ($u, $v) use ($b, $c) {
69
                    return ["{$b}{$c}{$u}" => $v];
70
                }, array_keys($a), array_values($a))
71
            );
72
        };
73
74 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...
75
            $a = count($a) ? call_user_func_array('array_merge', array_map(function ($k, $v) {
76
                return [str_replace(':', '', $k) => $v];
77
            }, array_keys($a), array_values($a))) : $a;
78
79
            return $a;
80
        };
81
82
        $array_clean_merge = function (array $a, $b) {
83
            return array_merge(
84
                $a,
85
                call_user_func_array(
86
                    'array_merge',
87
                    array_filter(
88
                        $b,
89
                        'strlen',
90
                        ARRAY_FILTER_USE_KEY
91
                    )
92
                )
93
            );
94
        };
95
96 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...
97
            $keys = preg_grep('/[\.\:]/', array_keys($a));
98
            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...
99
                foreach ($keys as $key) {
100
                    array_set($a, str_replace(':', '', $key), $a[$key]);
101
                    unset($a[$key]);
102
                }
103
            }
104
105
            return $a;
106
        };
107
108
        /** @var Field $field */
109
        foreach ($this->buildEmbeddedForm()->fields() as $field) {
110
            if (!$fieldRules = $field->getRules()) {
111
                continue;
112
            }
113
114
            $column = $field->column();
115
            $columns = is_array($column) ? $column : [$column];
116 View Code Duplication
            if ($field instanceof Field\MultipleSelect) {
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...
117
                $availInput[$column] = array_filter($availInput[$column], 'strlen');
118
                $availInput[$column] = $availInput[$column] ?: null;
119
            }
120
            /*
121
             *
122
             * For single column field format rules to:
123
             * [
124
             *     'extra.name' => 'required'
125
             *     'extra.email' => 'required'
126
             * ]
127
             *
128
             * For multiple column field with rules like 'required':
129
             * 'extra' => [
130
             *     'start' => 'start_at'
131
             *     'end'   => 'end_at',
132
             * ]
133
             *
134
             * format rules to:
135
             * [
136
             *     'extra.start_atstart' => 'required'
137
             *     'extra.end_atend' => 'required'
138
             * ]
139
             */
140
            $newColumn = array_map(function ($k, $v) use ($rel) {
141
                //Fix ResetInput Function! A Headache Implementation!
142
                return !$k ? "{$rel}.{$v}" : "{$rel}.{$v}:{$k}";
143
            }, array_keys($columns), array_values($columns));
144
145
            $fieldRules = is_array($fieldRules) ? implode('|', $fieldRules) : $fieldRules;
146
            $newRules = array_map(function ($v) use ($fieldRules, $availInput) {
147
                list($k, $c) = explode('.', $v);
148
                //Fix ResetInput Function! A Headache Implementation!
149
                $col = explode(':', $c)[0];
150
                if (!array_key_exists($col, $availInput[$k])) {
151
                    return [null => null];
152
                }
153
154
                if (is_array($availInput[$k][$col])) {
155
                    return $array_key_attach_str(preg_replace('/./', $fieldRules, $availInput[$k][$col]), $v, ':');
0 ignored issues
show
Bug introduced by
The variable $array_key_attach_str does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
156
                }
157
158
                return [$v => $fieldRules];
159
            }, $newColumn);
160
            $rules = $array_clean_merge($rules, $newRules);
161
162 View Code Duplication
            $newInput = array_map(function ($v) use ($availInput, $array_key_attach_str) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
163
                list($k, $c) = explode('.', $v);
164
                //Fix ResetInput Function! A Headache Implementation!
165
                $col = explode(':', $c)[0];
166
                if (!array_key_exists($col, $availInput[$k])) {
167
                    return [null => null];
168
                }
169
170
                if (is_array($availInput[$k][$col])) {
171
                    return $array_key_attach_str($availInput[$k][$col], $v, ':');
172
                }
173
174
                return [$v => $availInput[$k][$col]];
175
            }, $newColumn);
176
            $newInputs = $array_clean_merge($newInputs, $newInput);
177
178 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...
179
                list($k, $c) = explode('.', $v);
180
                //Fix ResetInput Function! A Headache Implementation!
181
                $col = explode(':', $c)[0];
182
                if (!array_key_exists($col, $availInput[$k])) {
183
                    return [null => null];
184
                }
185
186
                if (is_array($availInput[$k][$col])) {
187
                    return call_user_func_array('array_merge', array_map(function ($u) use ($v, $field) {
188
                        $w = $field->label();
189
                        //Fix ResetInput Function! A Headache Implementation!
190
                        $w .= is_array($field->column()) ? '['.explode(':', explode('.', $v)[2])[0].']' : '';
191
192
                        return ["{$v}:{$u}" => $w];
193
                    }, array_keys($availInput[$k][$col])));
194
                }
195
196
                $w = $field->label();
197
                //Fix ResetInput Function! A Headache Implementation!
198
                $w .= is_array($field->column()) ? '['.explode(':', explode('.', $v)[2])[0].']' : '';
199
200
                return [$v => $w];
201
            }, $newColumn);
202
            $attributes = $array_clean_merge($attributes, $newAttributes);
203
204 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...
205
                $newMessages = array_map(function ($v) use ($field, $availInput, $array_key_attach_str) {
206
                    list($k, $c) = explode('.', $v);
207
                    //Fix ResetInput Function! A Headache Implementation!
208
                    $col = explode(':', $c)[0];
209
                    if (!array_key_exists($col, $availInput[$k])) {
210
                        return [null => null];
211
                    }
212
                    if (is_array($availInput[$k][$col])) {
213
                        return call_user_func_array('array_merge', array_map(function ($u) use ($v, $field, $array_key_attach_str) {
214
                            return $array_key_attach_str($field->validationMessages, "{$v}:{$u}");
215
                        }, array_keys($availInput[$k][$col])));
216
                    }
217
218
                    return $array_key_attach_str($field->validationMessages, $v);
219
                }, $newColumn);
220
                $messages = $array_clean_merge($messages, $newMessages);
221
            }
222
        }
223
224
        $rules = array_filter($rules, 'strlen');
225
226
        if (empty($rules)) {
227
            return false;
228
        }
229
230
        $attributes = array_filter($attributes, 'strlen');
231
        $messages = array_filter($messages, 'strlen');
232
        $input = $array_key_clean_undot(array_filter($newInputs, 'strlen', ARRAY_FILTER_USE_KEY));
233
        $rules = $array_key_clean($rules);
234
        $attributes = $array_key_clean($attributes);
235
        $messages = $array_key_clean($messages);
236
237
        if (empty($input)) {
238
            $input = [$rel => $availInput];
239
        }
240
241
        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...
242
    }
243
244
    /**
245
     * Get data for Embedded form.
246
     *
247
     * Normally, data is obtained from the database.
248
     *
249
     * When the data validation errors, data is obtained from session flash.
250
     *
251
     * @return array
252
     */
253
    protected function getEmbeddedData()
254
    {
255
        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...
256
            return $old;
257
        }
258
259
        if (empty($this->value)) {
260
            return [];
261
        }
262
263
        if (is_string($this->value)) {
264
            return json_decode($this->value, true);
265
        }
266
267
        return (array) $this->value;
268
    }
269
270
    /**
271
     * Build a Embedded Form and fill data.
272
     *
273
     * @return EmbeddedForm
274
     */
275
    protected function buildEmbeddedForm()
276
    {
277
        $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...
278
279
        $form->setParent($this->form);
280
281
        call_user_func($this->builder, $form);
282
283
        $form->fill($this->getEmbeddedData());
284
285
        return $form;
286
    }
287
288
    /**
289
     * Render the form.
290
     *
291
     * @return \Illuminate\View\View
292
     */
293
    public function render()
294
    {
295
        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...
296
    }
297
}
298