Completed
Pull Request — master (#2622)
by
unknown
02:40
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
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 = [];
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::make($input, $rules, $this->validationMessages, $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...
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(array_dot($input)) as $key) {
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
            array_set($input, "{$this->column}.$newKey", $value);
193
            /*
194
             * forget the old key and value
195
             */
196
            array_forget($input, "{$this->column}.$key");
197
        }
198
    }
199
    
200
    /**
201
     * Get fields for Embedded form.
202
     * @return Collection
203
     */
204
    public function getFields(){
205
        return $this->buildEmbeddedForm()->fields();
206
    }
207
208
    /**
209
     * Get data for Embedded form.
210
     *
211
     * Normally, data is obtained from the database.
212
     *
213
     * When the data validation errors, data is obtained from session flash.
214
     *
215
     * @return array
216
     */
217
    protected function getEmbeddedData()
218
    {
219
        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...
220
            return $old;
221
        }
222
223
        if (empty($this->value)) {
224
            return [];
225
        }
226
227
        if (is_string($this->value)) {
228
            return json_decode($this->value, true);
229
        }
230
231
        return (array) $this->value;
232
    }
233
234
    /**
235
     * Build a Embedded Form and fill data.
236
     *
237
     * @return EmbeddedForm
238
     */
239
    protected function buildEmbeddedForm()
240
    {
241
        $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...
242
243
        $form->setParent($this->form);
244
245
        call_user_func($this->builder, $form);
246
247
        $form->fill($this->getEmbeddedData());
248
249
        return $form;
250
    }
251
252
    /**
253
     * Render the form.
254
     *
255
     * @return \Illuminate\View\View
256
     */
257
    public function render()
258
    {
259
        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...
260
    }
261
}
262