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

Embeds   A

Complexity

Total Complexity 36

Size/Duplication

Total Lines 272
Duplicated Lines 38.97 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
dl 106
loc 272
rs 9.52
c 0
b 0
f 0
wmc 36
lcom 1
cbo 3

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 13 13 3
A prepare() 0 6 1
F getValidator() 93 172 26
A getEmbeddedData() 0 16 4
A buildEmbeddedForm() 0 12 1
A render() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
class Embeds extends Field
10
{
11
    /**
12
     * @var \Closure
13
     */
14
    protected $builder = null;
15
    protected $view = 'admin::form.embeds';
16
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
        $rules = $attributes = $messages = $newInputs = [];
62
        $rel = $this->column;
63
        $availInput = $input;
64 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...
65
            return call_user_func_array(
66
                'array_merge',
67
                array_map(function ($u, $v) use ($b, $c) {
68
                    return ["{$b}{$c}{$u}" => $v];
69
                }, array_keys($a), array_values($a))
70
            );
71
        };
72
73 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...
74
            $a = count($a) ? call_user_func_array('array_merge', array_map(function ($k, $v) {
75
                return [str_replace(':', '', $k) => $v];
76
            }, array_keys($a), array_values($a))) : $a;
77
78
            return $a;
79
        };
80
81
        $array_clean_merge = function (array $a, $b) {
82
            return array_merge($a, call_user_func_array('array_merge', $b));
83
        };
84
85 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...
86
            $keys = preg_grep('/[\.\:]/', array_keys($a));
87
            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...
88
                foreach ($keys as $key) {
89
                    array_set($a, str_replace(':', '', $key), $a[$key]);
90
                    unset($a[$key]);
91
                }
92
            }
93
94
            return $a;
95
        };
96
97
        /** @var Field $field */
98
        foreach ($this->buildEmbeddedForm()->fields() as $field) {
99
            if (!$fieldRules = $field->getRules()) {
100
                continue;
101
            }
102
103
            $column = $field->column();
104
            $columns = is_array($column) ? $column : [$column];
105 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...
106
                $availInput[$column] = array_filter($availInput[$column], 'strlen');
107
                $availInput[$column] = $availInput[$column] ?: null;
108
            }
109
            /*
110
             *
111
             * For single column field format rules to:
112
             * [
113
             *     'extra.name' => 'required'
114
             *     'extra.email' => 'required'
115
             * ]
116
             *
117
             * For multiple column field with rules like 'required':
118
             * 'extra' => [
119
             *     'start' => 'start_at'
120
             *     'end'   => 'end_at',
121
             * ]
122
             *
123
             * format rules to:
124
             * [
125
             *     'extra.start_atstart' => 'required'
126
             *     'extra.end_atend' => 'required'
127
             * ]
128
             */
129
            $newColumn = array_map(function ($k, $v) use ($rel) {
130
                //Fix ResetInput Function! A Headache Implementation!
131
                return !$k ? "{$rel}.{$v}" : "{$rel}.{$v}:{$k}";
132
            }, array_keys($columns), array_values($columns));
133
134
            $fieldRules = is_array($fieldRules) ? implode('|', $fieldRules) : $fieldRules;
135 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...
136
                list($k, $c) = explode('.', $v);
137
                //Fix ResetInput Function! A Headache Implementation!
138
                $col = explode(':', $c)[0];
139
140
                if (array_key_exists($col, $availInput[$k]) && is_array($availInput[$k][$col])) {
141
                    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...
142
                }
143
144
                //May Have Problem in Dealing with File Upload in Edit Mode
145
                return [$v => $fieldRules];
146
            }, $newColumn);
147
            $rules = $array_clean_merge($rules, $newRules);
148
149 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...
150
                list($k, $c) = explode('.', $v);
151
                //Fix ResetInput Function! A Headache Implementation!
152
                $col = explode(':', $c)[0];
153
                if (!array_key_exists($col, $availInput[$k])) {
154
                    //May Have Problem in Dealing with File Upload in Edit Mode
155
                    return [$v => null];
156
                }
157
158
                if (array_key_exists($col, $availInput[$k]) && is_array($availInput[$k][$col])) {
159
                    return $array_key_attach_str($availInput[$k][$col], $v, ':');
160
                }
161
162
                return [$v => $availInput[$k][$col]];
163
            }, $newColumn);
164
            $newInputs = $array_clean_merge($newInputs, $newInput);
165
166 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...
167
                list($k, $c) = explode('.', $v);
168
                //Fix ResetInput Function! A Headache Implementation!
169
                $col = explode(':', $c)[0];
170
                if (array_key_exists($col, $availInput[$k]) && is_array($availInput[$k][$col])) {
171
                    return call_user_func_array('array_merge', array_map(function ($u) use ($v, $field) {
172
                        $w = $field->label();
173
                        //Fix ResetInput Function! A Headache Implementation!
174
                        $w .= is_array($field->column()) ? '['.explode(':', explode('.', $v)[2])[0].']' : '';
175
176
                        return ["{$v}:{$u}" => $w];
177
                    }, array_keys($availInput[$k][$col])));
178
                }
179
180
                //May Have Problem in Dealing with File Upload in Edit Mode
181
                $w = $field->label();
182
                //Fix ResetInput Function! A Headache Implementation!
183
                $w .= is_array($field->column()) ? '['.explode(':', explode('.', $v)[2])[0].']' : '';
184
185
                return [$v => $w];
186
            }, $newColumn);
187
            $attributes = $array_clean_merge($attributes, $newAttributes);
188
189 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...
190
                $newMessages = array_map(function ($v) use ($field, $availInput, $array_key_attach_str) {
191
                    list($k, $c) = explode('.', $v);
192
                    //Fix ResetInput Function! A Headache Implementation!
193
                    $col = explode(':', $c)[0];
194
                    if (array_key_exists($col, $availInput[$k]) && is_array($availInput[$k][$col])) {
195
                        return call_user_func_array('array_merge', array_map(function ($u) use ($v, $field, $array_key_attach_str) {
196
                            return $array_key_attach_str($field->validationMessages, "{$v}:{$u}");
197
                        }, array_keys($availInput[$k][$col])));
198
                    }
199
200
                    //May Have Problem in Dealing with File Upload in Edit Mode
201
                    return $array_key_attach_str($field->validationMessages, $v);
202
                }, $newColumn);
203
                $messages = $array_clean_merge($messages, $newMessages);
204
            }
205
        }
206
207
        $rules = array_filter($rules, 'strlen');
208
209
        if (empty($rules)) {
210
            return false;
211
        }
212
213
        $attributes = array_filter($attributes, 'strlen');
214
        $messages = array_filter($messages, 'strlen');
215
        $input = $array_key_clean_undot(array_filter($newInputs, 'strlen', ARRAY_FILTER_USE_KEY));
216
        $rules = $array_key_clean($rules);
217
        $attributes = $array_key_clean($attributes);
218
        $messages = $array_key_clean($messages);
219
220
        if (empty($input)) {
221
            $input = [$rel => $availInput];
222
        }
223
224
        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...
225
    }
226
227
    /**
228
     * Get data for Embedded form.
229
     *
230
     * Normally, data is obtained from the database.
231
     *
232
     * When the data validation errors, data is obtained from session flash.
233
     *
234
     * @return array
235
     */
236
    protected function getEmbeddedData()
237
    {
238
        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...
239
            return $old;
240
        }
241
242
        if (empty($this->value)) {
243
            return [];
244
        }
245
246
        if (is_string($this->value)) {
247
            return json_decode($this->value, true);
248
        }
249
250
        return (array) $this->value;
251
    }
252
253
    /**
254
     * Build a Embedded Form and fill data.
255
     *
256
     * @return EmbeddedForm
257
     */
258
    protected function buildEmbeddedForm()
259
    {
260
        $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...
261
262
        $form->setParent($this->form);
263
264
        call_user_func($this->builder, $form);
265
266
        $form->fill($this->getEmbeddedData());
267
268
        return $form;
269
    }
270
271
    /**
272
     * Render the form.
273
     *
274
     * @return \Illuminate\View\View
275
     */
276
    public function render()
277
    {
278
        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...
279
    }
280
}
281