Completed
Push — master ( 13677a...5137ae )
by Song
26s queued 11s
created

Embeds::isNested()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 4
rs 10
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\Arr;
8
use Illuminate\Support\Str;
9
10
class Embeds extends Field
11
{
12
    /**
13
     * @var \Closure
14
     */
15
    protected $builder = null;
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 = Arr::only($input, $this->column);
61
62
        $rules = $attributes = [];
63
64
        /** @var Field $field */
65
        foreach ($this->buildEmbeddedForm()->fields() as $field) {
66
            if (!$fieldRules = $field->getRules()) {
67
                continue;
68
            }
69
70
            $column = $field->column();
71
72
            /*
73
             *
74
             * For single column field format rules to:
75
             * [
76
             *     'extra.name' => 'required'
77
             *     'extra.email' => 'required'
78
             * ]
79
             *
80
             * For multiple column field with rules like 'required':
81
             * 'extra' => [
82
             *     'start' => 'start_at'
83
             *     'end'   => 'end_at',
84
             * ]
85
             *
86
             * format rules to:
87
             * [
88
             *     'extra.start_atstart' => 'required'
89
             *     'extra.end_atend' => 'required'
90
             * ]
91
             */
92
            if (is_array($column)) {
93
                foreach ($column as $key => $name) {
94
                    $rules["{$this->column}.$name$key"] = $fieldRules;
95
                }
96
97
                $this->resetInputKey($input, $column);
98
            } else {
99
                $rules["{$this->column}.$column"] = $fieldRules;
100
            }
101
102
            /**
103
             * For single column field format attributes to:
104
             * [
105
             *     'extra.name' => $label
106
             *     'extra.email' => $label
107
             * ].
108
             *
109
             * For multiple column field with rules like 'required':
110
             * 'extra' => [
111
             *     'start' => 'start_at'
112
             *     'end'   => 'end_at',
113
             * ]
114
             *
115
             * format rules to:
116
             * [
117
             *     'extra.start_atstart' => "$label[start_at]"
118
             *     'extra.end_atend' => "$label[end_at]"
119
             * ]
120
             */
121
            $attributes = array_merge(
122
                $attributes,
123
                $this->formatValidationAttribute($input, $field->label(), $column)
124
            );
125
        }
126
127
        if (empty($rules)) {
128
            return false;
129
        }
130
131
        return \validator($input, $rules, $this->getValidationMessages(), $attributes);
132
    }
133
134
    /**
135
     * Format validation attributes.
136
     *
137
     * @param array  $input
138
     * @param string $label
139
     * @param string $column
140
     *
141
     * @return array
142
     */
143 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...
144
    {
145
        $new = $attributes = [];
146
147
        if (is_array($column)) {
148
            foreach ($column as $index => $col) {
149
                $new[$col.$index] = $col;
150
            }
151
        }
152
153
        foreach (array_keys(Arr::dot($input)) as $key) {
0 ignored issues
show
Documentation introduced by
$input is of type array, but the function expects a object<Illuminate\Support\iterable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
154
            if (is_string($column)) {
155
                if (Str::endsWith($key, ".$column")) {
156
                    $attributes[$key] = $label;
157
                }
158
            } else {
159
                foreach ($new as $k => $val) {
160
                    if (Str::endsWith($key, ".$k")) {
161
                        $attributes[$key] = $label."[$val]";
162
                    }
163
                }
164
            }
165
        }
166
167
        return $attributes;
168
    }
169
170
    /**
171
     * Reset input key for validation.
172
     *
173
     * @param array $input
174
     * @param array $column $column is the column name array set
175
     *
176
     * @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...
177
     */
178
    public function resetInputKey(array &$input, array $column)
179
    {
180
        $column = array_flip($column);
181
182 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...
183
            if (!array_key_exists($key, $column)) {
184
                continue;
185
            }
186
187
            $newKey = $key.$column[$key];
188
189
            /*
190
             * set new key
191
             */
192
            Arr::set($input, "{$this->column}.$newKey", $value);
193
            /*
194
             * forget the old key and value
195
             */
196
            Arr::forget($input, "{$this->column}.$key");
197
        }
198
    }
199
200
    /**
201
     * Get data for Embedded form.
202
     *
203
     * Normally, data is obtained from the database.
204
     *
205
     * When the data validation errors, data is obtained from session flash.
206
     *
207
     * @return array
208
     */
209
    protected function getEmbeddedData()
210
    {
211
        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...
212
            return $old;
213
        }
214
215
        if (empty($this->value)) {
216
            return [];
217
        }
218
219
        if (is_string($this->value)) {
220
            return json_decode($this->value, true);
221
        }
222
223
        return (array) $this->value;
224
    }
225
226
    /**
227
     * Build a Embedded Form and fill data.
228
     *
229
     * @return EmbeddedForm
230
     */
231
    protected function buildEmbeddedForm()
232
    {
233
        $form = new EmbeddedForm($this->getEmbeddedColumnName());
0 ignored issues
show
Bug introduced by
It seems like $this->getEmbeddedColumnName() targeting Encore\Admin\Form\Field\...getEmbeddedColumnName() can also be of type array; however, Encore\Admin\Form\EmbeddedForm::__construct() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
234
235
        $form->setParent($this->form);
236
237
        call_user_func($this->builder, $form);
238
239
        $form->fill($this->getEmbeddedData());
240
241
        return $form;
242
    }
243
244
    /**
245
     * Determine the column name to use with the embedded form
246
     *
247
     * @return array|string
248
     */
249
    protected function getEmbeddedColumnName()
250
    {
251
        if ($this->isNested()) {
252
            return $this->elementName;
253
        }
254
255
        return $this->column;
256
    }
257
258
    /**
259
     * Check if the field is in a nested form
260
     *
261
     * @return bool
262
     */
263
    protected function isNested()
264
    {
265
        return !empty($this->elementName);
266
    }
267
268
    /**
269
     * Render the form.
270
     *
271
     * @return \Illuminate\View\View
272
     */
273
    public function render()
274
    {
275
        return parent::fieldRender(['form' => $this->buildEmbeddedForm()]);
0 ignored issues
show
Bug Compatibility introduced by
The expression parent::fieldRender(arra...>buildEmbeddedForm())); of type Illuminate\Contracts\Vie...minate\View\View|string adds the type Illuminate\Contracts\View\Factory to the return on line 275 which is incompatible with the return type declared by the interface Illuminate\Contracts\Support\Renderable::render of type string.
Loading history...
Comprehensibility Bug introduced by
It seems like you call parent on a different method (fieldRender() instead of render()). Are you sure this is correct? If so, you might want to change this to $this->fieldRender().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
276
    }
277
}
278