Completed
Push — master ( 52d4f0...7cba09 )
by Song
02:16
created

Form::fill()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 4
nop 1
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
1
<?php
2
3
namespace Encore\Admin\Widgets;
4
5
use Encore\Admin\Form as BaseForm;
6
use Encore\Admin\Form\Field;
7
use Illuminate\Contracts\Support\Arrayable;
8
use Illuminate\Contracts\Support\Renderable;
9
use Illuminate\Support\Arr;
10
11
/**
12
 * Class Form.
13
 *
14
 * @method Field\Text           text($name, $label = '')
15
 * @method Field\Password       password($name, $label = '')
16
 * @method Field\Checkbox       checkbox($name, $label = '')
17
 * @method Field\Radio          radio($name, $label = '')
18
 * @method Field\Select         select($name, $label = '')
19
 * @method Field\MultipleSelect multipleSelect($name, $label = '')
20
 * @method Field\Textarea       textarea($name, $label = '')
21
 * @method Field\Hidden         hidden($name, $label = '')
22
 * @method Field\Id             id($name, $label = '')
23
 * @method Field\Ip             ip($name, $label = '')
24
 * @method Field\Url            url($name, $label = '')
25
 * @method Field\Color          color($name, $label = '')
26
 * @method Field\Email          email($name, $label = '')
27
 * @method Field\Mobile         mobile($name, $label = '')
28
 * @method Field\Slider         slider($name, $label = '')
29
 * @method Field\File           file($name, $label = '')
30
 * @method Field\Image          image($name, $label = '')
31
 * @method Field\Date           date($name, $label = '')
32
 * @method Field\Datetime       datetime($name, $label = '')
33
 * @method Field\Time           time($name, $label = '')
34
 * @method Field\Year           year($column, $label = '')
35
 * @method Field\Month          month($column, $label = '')
36
 * @method Field\DateRange      dateRange($start, $end, $label = '')
37
 * @method Field\DateTimeRange  dateTimeRange($start, $end, $label = '')
38
 * @method Field\TimeRange      timeRange($start, $end, $label = '')
39
 * @method Field\Number         number($name, $label = '')
40
 * @method Field\Currency       currency($name, $label = '')
41
 * @method Field\SwitchField    switch($name, $label = '')
42
 * @method Field\Display        display($name, $label = '')
43
 * @method Field\Rate           rate($name, $label = '')
44
 * @method Field\Divide         divide()
45
 * @method Field\Decimal        decimal($column, $label = '')
46
 * @method Field\Html           html($html)
47
 * @method Field\Tags           tags($column, $label = '')
48
 * @method Field\Icon           icon($column, $label = '')
49
 * @method Field\Captcha        captcha($column, $label = '')
50
 * @method Field\Listbox        listbox($column, $label = '')
51
 * @method Field\Table          table($column, $label, $builder)
52
 * @method Field\Timezone       timezone($column, $label = '')
53
 */
54
class Form implements Renderable
55
{
56
    /**
57
     * @var Field[]
58
     */
59
    protected $fields = [];
60
61
    /**
62
     * @var array
63
     */
64
    protected $data = [];
65
66
    /**
67
     * @var array
68
     */
69
    protected $attributes = [];
70
71
    /**
72
     * Available buttons.
73
     *
74
     * @var array
75
     */
76
    protected $buttons = ['reset', 'submit'];
77
78
    /**
79
     * Width for label and submit field.
80
     *
81
     * @var array
82
     */
83
    protected $width = [
84
        'label' => 2,
85
        'field' => 8,
86
    ];
87
88
    /**
89
     * Form constructor.
90
     *
91
     * @param array $data
92
     */
93
    public function __construct($data = [])
94
    {
95
        $this->fill($data);
96
97
        $this->initFormAttributes();
98
    }
99
100
    /**
101
     * Fill data to form fields.
102
     *
103
     * @param array $data
104
     * @return $this
105
     */
106
    public function fill($data = [])
107
    {
108
        if ($data instanceof Arrayable) {
109
            $data = $data->toArray();
110
        }
111
112
        if (!empty($data)) {
113
            $this->data = $data;
114
        }
115
116
        return $this;
117
    }
118
119
    /**
120
     * Initialize the form attributes.
121
     */
122
    protected function initFormAttributes()
123
    {
124
        $this->attributes = [
125
            'method'         => 'POST',
126
            'action'         => '',
127
            'class'          => 'form-horizontal',
128
            'accept-charset' => 'UTF-8',
129
            'pjax-container' => true,
130
        ];
131
    }
132
133
    /**
134
     * Action uri of the form.
135
     *
136
     * @param string $action
137
     *
138
     * @return $this
139
     */
140
    public function action($action)
141
    {
142
        return $this->attribute('action', $action);
143
    }
144
145
    /**
146
     * Method of the form.
147
     *
148
     * @param string $method
149
     *
150
     * @return $this
151
     */
152
    public function method($method = 'POST')
153
    {
154
        if (strtolower($method) == 'put') {
155
            $this->hidden('_method')->default($method);
156
157
            return $this;
158
        }
159
160
        return $this->attribute('method', strtoupper($method));
161
    }
162
163
    /**
164
     * Add form attributes.
165
     *
166
     * @param string|array $attr
167
     * @param string       $value
168
     *
169
     * @return $this
170
     */
171
    public function attribute($attr, $value = '')
172
    {
173
        if (is_array($attr)) {
174
            foreach ($attr as $key => $value) {
175
                $this->attribute($key, $value);
176
            }
177
        } else {
178
            $this->attributes[$attr] = $value;
179
        }
180
181
        return $this;
182
    }
183
184
    /**
185
     * Disable Pjax.
186
     *
187
     * @return $this
188
     */
189
    public function disablePjax()
190
    {
191
        Arr::forget($this->attributes, 'pjax-container');
192
193
        return $this;
194
    }
195
196
    /**
197
     * Disable reset button.
198
     *
199
     * @return $this
200
     */
201
    public function disableReset()
202
    {
203
        array_delete($this->buttons, 'reset');
204
205
        return $this;
206
    }
207
208
    /**
209
     * Disable submit button.
210
     *
211
     * @return $this
212
     */
213
    public function disableSubmit()
214
    {
215
        array_delete($this->buttons, 'submit');
216
217
        return $this;
218
    }
219
220
    /**
221
     * Set field and label width in current form.
222
     *
223
     * @param int $fieldWidth
224
     * @param int $labelWidth
225
     *
226
     * @return $this
227
     */
228
    public function setWidth($fieldWidth = 8, $labelWidth = 2)
229
    {
230
        collect($this->fields)->each(function ($field) use ($fieldWidth, $labelWidth) {
231
            /* @var Field $field  */
232
            $field->setWidth($fieldWidth, $labelWidth);
233
        });
234
235
        // set this width
236
        $this->width = [
237
            'label' => $labelWidth,
238
            'field' => $fieldWidth,
239
        ];
240
241
        return $this;
242
    }
243
244
    /**
245
     * Find field class with given name.
246
     *
247
     * @param string $method
248
     *
249
     * @return bool|string
250
     */
251
    public static function findFieldClass($method)
252
    {
253
        $class = Arr::get(BaseForm::$availableFields, $method);
254
255
        if (class_exists($class)) {
256
            return $class;
257
        }
258
259
        return false;
260
    }
261
262
    /**
263
     * Determine if the form has field type.
264
     *
265
     * @param string $name
266
     *
267
     * @return bool
268
     */
269
    public function hasField($name)
270
    {
271
        return isset(BaseForm::$availableFields[$name]);
272
    }
273
274
    /**
275
     * Add a form field to form.
276
     *
277
     * @param Field $field
278
     *
279
     * @return $this
280
     */
281
    public function pushField(Field &$field)
282
    {
283
        array_push($this->fields, $field);
284
285
        return $this;
286
    }
287
288
    /**
289
     * Get all fields of form.
290
     *
291
     * @return Field[]
292
     */
293
    public function fields()
294
    {
295
        return $this->fields;
296
    }
297
298
    /**
299
     * Get variables for render form.
300
     *
301
     * @return array
302
     */
303
    protected function getVariables()
304
    {
305
        foreach ($this->fields as $field) {
306
            $field->fill($this->data);
307
        }
308
309
        return [
310
            'fields'     => $this->fields,
311
            'attributes' => $this->formatAttribute(),
312
            'method'     => $this->attributes['method'],
313
            'buttons'    => $this->buttons,
314
            'width'      => $this->width,
315
        ];
316
    }
317
318
    /**
319
     * Format form attributes form array to html.
320
     *
321
     * @param array $attributes
322
     *
323
     * @return string
324
     */
325
    public function formatAttribute($attributes = [])
326
    {
327
        $attributes = $attributes ?: $this->attributes;
328
329
        if ($this->hasFile()) {
330
            $attributes['enctype'] = 'multipart/form-data';
331
        }
332
333
        $html = [];
334
        foreach ($attributes as $key => $val) {
335
            $html[] = "$key=\"$val\"";
336
        }
337
338
        return implode(' ', $html) ?: '';
339
    }
340
341
    /**
342
     * Determine if form fields has files.
343
     *
344
     * @return bool
345
     */
346
    public function hasFile()
347
    {
348
        foreach ($this->fields as $field) {
349
            if ($field instanceof Field\File) {
350
                return true;
351
            }
352
        }
353
354
        return false;
355
    }
356
357
    /**
358
     * Generate a Field object and add to form builder if Field exists.
359
     *
360
     * @param string $method
361
     * @param array  $arguments
362
     *
363
     * @return Field|null
364
     */
365
    public function __call($method, $arguments)
366
    {
367
        if ($className = static::findFieldClass($method)) {
368
            $name = Arr::get($arguments, 0, '');
369
370
            $element = new $className($name, array_slice($arguments, 1));
371
372
            $this->pushField($element);
373
374
            return $element;
375
        }
376
    }
377
378
    /**
379
     * Render the form.
380
     *
381
     * @return string
382
     */
383
    public function render()
384
    {
385
        return view('admin::widgets.form', $this->getVariables())->render();
0 ignored issues
show
Bug introduced by
The method render 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...
386
    }
387
388
    /**
389
     * Output as string.
390
     *
391
     * @return string
392
     */
393
    public function __toString()
394
    {
395
        return $this->render();
396
    }
397
}
398