Completed
Push — master ( ca14f0...c2f74e )
by Song
02:26
created

Field::creationRules()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Encore\Admin\Form;
4
5
use Closure;
6
use Encore\Admin\Admin;
7
use Encore\Admin\Form;
8
use Illuminate\Contracts\Support\Arrayable;
9
use Illuminate\Contracts\Support\Renderable;
10
use Illuminate\Support\Arr;
11
use Illuminate\Support\Str;
12
use Illuminate\Support\Traits\Macroable;
13
14
/**
15
 * Class Field.
16
 */
17
class Field implements Renderable
18
{
19
    use Macroable;
20
21
    const FILE_DELETE_FLAG = '_file_del_';
22
    const FILE_SORT_FLAG = '_file_sort_';
23
24
    /**
25
     * Element id.
26
     *
27
     * @var array|string
28
     */
29
    protected $id;
30
31
    /**
32
     * Element value.
33
     *
34
     * @var mixed
35
     */
36
    protected $value;
37
38
    /**
39
     * Data of all original columns of value.
40
     *
41
     * @var mixed
42
     */
43
    protected $data;
44
45
    /**
46
     * Field original value.
47
     *
48
     * @var mixed
49
     */
50
    protected $original;
51
52
    /**
53
     * Field default value.
54
     *
55
     * @var mixed
56
     */
57
    protected $default;
58
59
    /**
60
     * Element label.
61
     *
62
     * @var string
63
     */
64
    protected $label = '';
65
66
    /**
67
     * Column name.
68
     *
69
     * @var string|array
70
     */
71
    protected $column = '';
72
73
    /**
74
     * Form element name.
75
     *
76
     * @var string
77
     */
78
    protected $elementName = [];
79
80
    /**
81
     * Form element classes.
82
     *
83
     * @var array
84
     */
85
    protected $elementClass = [];
86
87
    /**
88
     * Variables of elements.
89
     *
90
     * @var array
91
     */
92
    protected $variables = [];
93
94
    /**
95
     * Options for specify elements.
96
     *
97
     * @var array
98
     */
99
    protected $options = [];
100
101
    /**
102
     * Checked for specify elements.
103
     *
104
     * @var array
105
     */
106
    protected $checked = [];
107
108
    /**
109
     * Validation rules.
110
     *
111
     * @var array|\Closure
112
     */
113
    protected $rules = [];
114
115
    /**
116
     * The validation rules for creation.
117
     *
118
     * @var array|\Closure
119
     */
120
    public $creationRules = [];
121
122
    /**
123
     * The validation rules for updates.
124
     *
125
     * @var array|\Closure
126
     */
127
    public $updateRules = [];
128
129
    /**
130
     * @var \Closure
131
     */
132
    protected $validator;
133
134
    /**
135
     * Validation messages.
136
     *
137
     * @var array
138
     */
139
    protected $validationMessages = [];
140
141
    /**
142
     * Css required by this field.
143
     *
144
     * @var array
145
     */
146
    protected static $css = [];
147
148
    /**
149
     * Js required by this field.
150
     *
151
     * @var array
152
     */
153
    protected static $js = [];
154
155
    /**
156
     * Script for field.
157
     *
158
     * @var string
159
     */
160
    protected $script = '';
161
162
    /**
163
     * Element attributes.
164
     *
165
     * @var array
166
     */
167
    protected $attributes = [];
168
169
    /**
170
     * Parent form.
171
     *
172
     * @var Form
173
     */
174
    protected $form = null;
175
176
    /**
177
     * View for field to render.
178
     *
179
     * @var string
180
     */
181
    protected $view = '';
182
183
    /**
184
     * Help block.
185
     *
186
     * @var array
187
     */
188
    protected $help = [];
189
190
    /**
191
     * Key for errors.
192
     *
193
     * @var mixed
194
     */
195
    protected $errorKey;
196
197
    /**
198
     * Placeholder for this field.
199
     *
200
     * @var string|array
201
     */
202
    protected $placeholder;
203
204
    /**
205
     * Width for label and field.
206
     *
207
     * @var array
208
     */
209
    protected $width = [
210
        'label' => 2,
211
        'field' => 8,
212
    ];
213
214
    /**
215
     * If the form horizontal layout.
216
     *
217
     * @var bool
218
     */
219
    protected $horizontal = true;
220
221
    /**
222
     * column data format.
223
     *
224
     * @var \Closure
225
     */
226
    protected $customFormat = null;
227
228
    /**
229
     * @var bool
230
     */
231
    protected $display = true;
232
233
    /**
234
     * @var array
235
     */
236
    protected $labelClass = [];
237
238
    /**
239
     * @var array
240
     */
241
    protected $groupClass = [];
242
243
    /**
244
     * @var \Closure
245
     */
246
    protected $callback;
247
248
    /**
249
     * @var bool
250
     */
251
    public $isJsonType = false;
252
253
    /**
254
     * Field constructor.
255
     *
256
     * @param       $column
257
     * @param array $arguments
258
     */
259
    public function __construct($column = '', $arguments = [])
260
    {
261
        $this->column = $this->formatColumn($column);
262
        $this->label = $this->formatLabel($arguments);
263
        $this->id = $this->formatId($column);
264
    }
265
266
    /**
267
     * Get assets required by this field.
268
     *
269
     * @return array
270
     */
271
    public static function getAssets()
272
    {
273
        return [
274
            'css' => static::$css,
275
            'js'  => static::$js,
276
        ];
277
    }
278
279
    /**
280
     * Format the field column name.
281
     *
282
     * @param string $column
283
     *
284
     * @return mixed|string
285
     */
286
    protected function formatColumn($column = '')
287
    {
288
        if (Str::contains($column, '->')) {
289
            $this->isJsonType = true;
290
291
            $column = str_replace('->', '.', $column);
292
        }
293
294
        return $column;
295
    }
296
297
    /**
298
     * Format the field element id.
299
     *
300
     * @param string|array $column
301
     *
302
     * @return string|array
303
     */
304
    protected function formatId($column)
305
    {
306
        return str_replace('.', '_', $column);
307
    }
308
309
    /**
310
     * Format the label value.
311
     *
312
     * @param array $arguments
313
     *
314
     * @return string
315
     */
316
    protected function formatLabel($arguments = [])
317
    {
318
        $column = is_array($this->column) ? current($this->column) : $this->column;
319
320
        $label = isset($arguments[0]) ? $arguments[0] : ucfirst($column);
321
322
        return str_replace(['.', '_', '->'], ' ', $label);
323
    }
324
325
    /**
326
     * Format the name of the field.
327
     *
328
     * @param string $column
329
     *
330
     * @return array|mixed|string
331
     */
332
    protected function formatName($column)
333
    {
334
        if (is_string($column)) {
335
            if (Str::contains($column, '->')) {
336
                $name = explode('->', $column);
337
            } else {
338
                $name = explode('.', $column);
339
            }
340
341
            if (count($name) == 1) {
342
                return $name[0];
343
            }
344
345
            $html = array_shift($name);
346
            foreach ($name as $piece) {
347
                $html .= "[$piece]";
348
            }
349
350
            return $html;
351
        }
352
353
        if (is_array($this->column)) {
354
            $names = [];
355
            foreach ($this->column as $key => $name) {
356
                $names[$key] = $this->formatName($name);
357
            }
358
359
            return $names;
360
        }
361
362
        return '';
363
    }
364
365
    /**
366
     * Set form element name.
367
     *
368
     * @param string $name
369
     *
370
     * @return $this
371
     *
372
     * @author Edwin Hui
373
     */
374
    public function setElementName($name)
375
    {
376
        $this->elementName = $name;
377
378
        return $this;
379
    }
380
381
    /**
382
     * Fill data to the field.
383
     *
384
     * @param array $data
385
     *
386
     * @return void
387
     */
388 View Code Duplication
    public function fill($data)
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...
389
    {
390
        $this->data = $data;
391
392
        if (is_array($this->column)) {
393
            foreach ($this->column as $key => $column) {
394
                $this->value[$key] = Arr::get($data, $column);
395
            }
396
397
            return;
398
        }
399
400
        $this->value = Arr::get($data, $this->column);
401
402
        $this->formatValue();
403
    }
404
405
    /**
406
     * Format value by passing custom formater.
407
     */
408
    protected function formatValue()
409
    {
410
        if (isset($this->customFormat) && $this->customFormat instanceof \Closure) {
411
            $this->value = call_user_func($this->customFormat, $this->value);
412
        }
413
    }
414
415
    /**
416
     * custom format form column data when edit.
417
     *
418
     * @param \Closure $call
419
     *
420
     * @return $this
421
     */
422
    public function customFormat(\Closure $call)
423
    {
424
        $this->customFormat = $call;
425
426
        return $this;
427
    }
428
429
    /**
430
     * Set original value to the field.
431
     *
432
     * @param array $data
433
     *
434
     * @return void
435
     */
436 View Code Duplication
    public function setOriginal($data)
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...
437
    {
438
        if (is_array($this->column)) {
439
            foreach ($this->column as $key => $column) {
440
                $this->original[$key] = Arr::get($data, $column);
441
            }
442
443
            return;
444
        }
445
446
        $this->original = Arr::get($data, $this->column);
447
    }
448
449
    /**
450
     * @param Form $form
451
     *
452
     * @return $this
453
     */
454
    public function setForm(Form $form = null)
455
    {
456
        $this->form = $form;
457
458
        return $this;
459
    }
460
461
    /**
462
     * Set width for field and label.
463
     *
464
     * @param int $field
465
     * @param int $label
466
     *
467
     * @return $this
468
     */
469
    public function setWidth($field = 8, $label = 2)
470
    {
471
        $this->width = [
472
            'label' => $label,
473
            'field' => $field,
474
        ];
475
476
        return $this;
477
    }
478
479
    /**
480
     * Set the field options.
481
     *
482
     * @param array $options
483
     *
484
     * @return $this
485
     */
486 View Code Duplication
    public function options($options = [])
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...
487
    {
488
        if ($options instanceof Arrayable) {
489
            $options = $options->toArray();
490
        }
491
492
        $this->options = array_merge($this->options, $options);
493
494
        return $this;
495
    }
496
497
    /**
498
     * Set the field option checked.
499
     *
500
     * @param array $checked
501
     *
502
     * @return $this
503
     */
504 View Code Duplication
    public function checked($checked = [])
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...
505
    {
506
        if ($checked instanceof Arrayable) {
507
            $checked = $checked->toArray();
508
        }
509
510
        $this->checked = array_merge($this->checked, $checked);
511
512
        return $this;
513
    }
514
515
    /**
516
     * Add `required` attribute to current field if has required rule,
517
     * except file and image fields.
518
     *
519
     * @param array $rules
520
     */
521
    protected function addRequiredAttribute($rules)
522
    {
523
        if (!is_array($rules)) {
524
            return;
525
        }
526
527
        if (!in_array('required', $rules)) {
528
            return;
529
        }
530
531
        if ($this instanceof Form\Field\MultipleFile
532
            || $this instanceof Form\Field\File) {
533
            return;
534
        }
535
536
        $this->required();
537
    }
538
539
    /**
540
     * If has `required` rule, add required attribute to this field.
541
     */
542
    protected function addRequiredAttributeFromRules()
543
    {
544
        if (is_null($this->data)) {
545
            // Create page
546
            $rules = $this->creationRules ?: $this->rules;
547
        } else {
548
            // Update page
549
            $rules = $this->updateRules ?: $this->rules;
550
        }
551
552
        $this->addRequiredAttribute($rules);
0 ignored issues
show
Bug introduced by
It seems like $rules can also be of type object<Closure>; however, Encore\Admin\Form\Field::addRequiredAttribute() does only seem to accept array, 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...
553
    }
554
555
    /**
556
     * Format validation rules.
557
     *
558
     * @param array|string $rules
559
     *
560
     * @return array
561
     */
562
    protected function formatRules($rules)
563
    {
564
        if (is_string($rules)) {
565
            $rules = array_filter(explode('|', $rules));
566
        }
567
568
        return array_filter((array) $rules);
569
    }
570
571
    /**
572
     * @param string|array|Closure $input
573
     * @param string|array         $original
574
     *
575
     * @return array|Closure
576
     */
577
    protected function mergeRules($input, $original)
578
    {
579
        if ($input instanceof Closure) {
580
            $rules = $input;
581
        } else {
582
            if (!empty($original)) {
583
                $original = $this->formatRules($original);
584
            }
585
586
            $rules = array_merge($original, $this->formatRules($input));
587
        }
588
589
        return $rules;
590
    }
591
592
    /**
593
     * Set the validation rules for the field.
594
     *
595
     * @param array|callable|string $rules
596
     * @param array                 $messages
597
     *
598
     * @return $this
599
     */
600 View Code Duplication
    public function rules($rules = null, $messages = [])
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...
601
    {
602
        $this->rules = $this->mergeRules($rules, $this->rules);
0 ignored issues
show
Documentation introduced by
$rules is of type callable|null, but the function expects a string|array|object<Closure>.

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...
Bug introduced by
It seems like $this->rules can also be of type object<Closure>; however, Encore\Admin\Form\Field::mergeRules() does only seem to accept string|array, 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...
603
604
        $this->setValidationMessages('default', $messages);
605
606
        return $this;
607
    }
608
609
    /**
610
     * Set the update validation rules for the field.
611
     *
612
     * @param array|callable|string $rules
613
     * @param array                 $messages
614
     *
615
     * @return $this
616
     */
617 View Code Duplication
    public function updateRules($rules = null, $messages = [])
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...
618
    {
619
        $this->updateRules = $this->mergeRules($rules, $this->updateRules);
0 ignored issues
show
Documentation introduced by
$rules is of type callable|null, but the function expects a string|array|object<Closure>.

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...
Bug introduced by
It seems like $this->updateRules can also be of type object<Closure>; however, Encore\Admin\Form\Field::mergeRules() does only seem to accept string|array, 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...
620
621
        $this->setValidationMessages('update', $messages);
622
623
        return $this;
624
    }
625
626
    /**
627
     * Set the creation validation rules for the field.
628
     *
629
     * @param array|callable|string $rules
630
     * @param array                 $messages
631
     *
632
     * @return $this
633
     */
634
    public function creationRules($rules = null, $messages = [])
635
    {
636
        $this->creationRules = $this->mergeRules($rules, $this->creationRules);
0 ignored issues
show
Documentation introduced by
$rules is of type callable|null, but the function expects a string|array|object<Closure>.

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...
Bug introduced by
It seems like $this->creationRules can also be of type object<Closure>; however, Encore\Admin\Form\Field::mergeRules() does only seem to accept string|array, 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...
637
638
        $this->setValidationMessages('creation', $messages);
639
640
        return $this;
641
    }
642
643
    /**
644
     * Set validation messages for column.
645
     *
646
     * @param string $key
647
     * @param array  $messages
648
     *
649
     * @return $this
650
     */
651
    public function setValidationMessages($key, array $messages)
652
    {
653
        $this->validationMessages[$key] = $messages;
654
655
        return $this;
656
    }
657
658
    /**
659
     * Get validation messages for the field.
660
     *
661
     * @return array|mixed
662
     */
663
    public function getValidationMessages()
664
    {
665
        // Default validation message.
666
        $messages = $this->validationMessages['default'] ?? [];
667
668
        if (request()->isMethod('POST')) {
669
            $messages = $this->validationMessages['creation'] ?? $messages;
670
        } elseif (request()->isMethod('PUT')) {
671
            $messages = $this->validationMessages['update'] ?? $messages;
672
        }
673
674
        return $messages;
675
    }
676
677
    /**
678
     * Get field validation rules.
679
     *
680
     * @return string
681
     */
682
    protected function getRules()
683
    {
684
        if (request()->isMethod('POST')) {
685
            $rules = $this->creationRules ?: $this->rules;
686
        } elseif (request()->isMethod('PUT')) {
687
            $rules = $this->updateRules ?: $this->rules;
688
        } else {
689
            $rules = $this->rules;
690
        }
691
692
        if ($rules instanceof \Closure) {
693
            $rules = $rules->call($this, $this->form);
694
        }
695
696
        if (is_string($rules)) {
697
            $rules = array_filter(explode('|', $rules));
698
        }
699
700
        if (!$this->form) {
701
            return $rules;
702
        }
703
704
        if (!$id = $this->form->model()->getKey()) {
705
            return $rules;
706
        }
707
708
        if (is_array($rules)) {
709
            foreach ($rules as &$rule) {
710
                if (is_string($rule)) {
711
                    $rule = str_replace('{{id}}', $id, $rule);
712
                }
713
            }
714
        }
715
716
        return $rules;
717
    }
718
719
    /**
720
     * Remove a specific rule by keyword.
721
     *
722
     * @param string $rule
723
     *
724
     * @return void
725
     */
726
    protected function removeRule($rule)
727
    {
728
        if (is_array($this->rules)) {
729
            array_delete($this->rules, $rule);
730
731
            return;
732
        }
733
734
        if (!is_string($this->rules)) {
735
            return;
736
        }
737
738
        $pattern = "/{$rule}[^\|]?(\||$)/";
739
        $this->rules = preg_replace($pattern, '', $this->rules, -1);
0 ignored issues
show
Documentation Bug introduced by
It seems like preg_replace($pattern, '', $this->rules, -1) of type string is incompatible with the declared type array|object<Closure> of property $rules.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
740
    }
741
742
    /**
743
     * Set field validator.
744
     *
745
     * @param callable $validator
746
     *
747
     * @return $this
748
     */
749
    public function validator(callable $validator)
750
    {
751
        $this->validator = $validator;
0 ignored issues
show
Documentation Bug introduced by
It seems like $validator of type callable is incompatible with the declared type object<Closure> of property $validator.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
752
753
        return $this;
754
    }
755
756
    /**
757
     * Get key for error message.
758
     *
759
     * @return string
760
     */
761
    public function getErrorKey()
762
    {
763
        return $this->errorKey ?: $this->column;
764
    }
765
766
    /**
767
     * Set key for error message.
768
     *
769
     * @param string $key
770
     *
771
     * @return $this
772
     */
773
    public function setErrorKey($key)
774
    {
775
        $this->errorKey = $key;
776
777
        return $this;
778
    }
779
780
    /**
781
     * Set or get value of the field.
782
     *
783
     * @param null $value
784
     *
785
     * @return mixed
786
     */
787 View Code Duplication
    public function value($value = null)
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...
788
    {
789
        if (is_null($value)) {
790
            return is_null($this->value) ? $this->getDefault() : $this->value;
791
        }
792
793
        $this->value = $value;
794
795
        return $this;
796
    }
797
798
    /**
799
     * Set or get data.
800
     *
801
     * @param array $data
802
     *
803
     * @return $this
804
     */
805
    public function data(array $data = null)
806
    {
807
        if (is_null($data)) {
808
            return $this->data;
809
        }
810
811
        $this->data = $data;
812
813
        return $this;
814
    }
815
816
    /**
817
     * Set default value for field.
818
     *
819
     * @param $default
820
     *
821
     * @return $this
822
     */
823
    public function default($default)
824
    {
825
        $this->default = $default;
826
827
        return $this;
828
    }
829
830
    /**
831
     * Get default value.
832
     *
833
     * @return mixed
834
     */
835
    public function getDefault()
836
    {
837
        if ($this->default instanceof \Closure) {
838
            return call_user_func($this->default, $this->form);
839
        }
840
841
        return $this->default;
842
    }
843
844
    /**
845
     * Set help block for current field.
846
     *
847
     * @param string $text
848
     * @param string $icon
849
     *
850
     * @return $this
851
     */
852
    public function help($text = '', $icon = 'fa-info-circle')
853
    {
854
        $this->help = compact('text', 'icon');
855
856
        return $this;
857
    }
858
859
    /**
860
     * Get column of the field.
861
     *
862
     * @return string|array
863
     */
864
    public function column()
865
    {
866
        return $this->column;
867
    }
868
869
    /**
870
     * Get label of the field.
871
     *
872
     * @return string
873
     */
874
    public function label()
875
    {
876
        return $this->label;
877
    }
878
879
    /**
880
     * Get original value of the field.
881
     *
882
     * @return mixed
883
     */
884
    public function original()
885
    {
886
        return $this->original;
887
    }
888
889
    /**
890
     * Get validator for this field.
891
     *
892
     * @param array $input
893
     *
894
     * @return bool|\Illuminate\Contracts\Validation\Validator|mixed
895
     */
896
    public function getValidator(array $input)
897
    {
898
        if ($this->validator) {
899
            return $this->validator->call($this, $input);
900
        }
901
902
        $rules = $attributes = [];
903
904
        if (!$fieldRules = $this->getRules()) {
905
            return false;
906
        }
907
908
        if (is_string($this->column)) {
909
            if (!Arr::has($input, $this->column)) {
910
                return false;
911
            }
912
913
            $input = $this->sanitizeInput($input, $this->column);
914
915
            $rules[$this->column] = $fieldRules;
916
            $attributes[$this->column] = $this->label;
917
        }
918
919
        if (is_array($this->column)) {
920
            foreach ($this->column as $key => $column) {
921
                if (!array_key_exists($column, $input)) {
922
                    continue;
923
                }
924
                $input[$column.$key] = Arr::get($input, $column);
925
                $rules[$column.$key] = $fieldRules;
926
                $attributes[$column.$key] = $this->label."[$column]";
927
            }
928
        }
929
930
        return \validator($input, $rules, $this->getValidationMessages(), $attributes);
931
    }
932
933
    /**
934
     * Sanitize input data.
935
     *
936
     * @param array  $input
937
     * @param string $column
938
     *
939
     * @return array
940
     */
941
    protected function sanitizeInput($input, $column)
942
    {
943
        if ($this instanceof Field\MultipleSelect) {
944
            $value = Arr::get($input, $column);
945
            Arr::set($input, $column, array_filter($value));
946
        }
947
948
        return $input;
949
    }
950
951
    /**
952
     * Add html attributes to elements.
953
     *
954
     * @param array|string $attribute
955
     * @param mixed        $value
956
     *
957
     * @return $this
958
     */
959
    public function attribute($attribute, $value = null)
960
    {
961
        if (is_array($attribute)) {
962
            $this->attributes = array_merge($this->attributes, $attribute);
963
        } else {
964
            $this->attributes[$attribute] = (string) $value;
965
        }
966
967
        return $this;
968
    }
969
970
    /**
971
     * Set Field style.
972
     *
973
     * @param string $attr
974
     * @param string $value
975
     *
976
     * @return $this
977
     */
978
    public function style($attr, $value)
979
    {
980
        return $this->attribute('style', "{$attr}: {$value}");
981
    }
982
983
    /**
984
     * Set Field width.
985
     *
986
     * @param string $width
987
     *
988
     * @return $this
989
     */
990
    public function width($width)
991
    {
992
        return $this->style('width', $width);
993
    }
994
995
    /**
996
     * Specifies a regular expression against which to validate the value of the input.
997
     *
998
     * @param string $regexp
999
     *
1000
     * @return $this
1001
     */
1002
    public function pattern($regexp)
1003
    {
1004
        return $this->attribute('pattern', $regexp);
1005
    }
1006
1007
    /**
1008
     * set the input filed required.
1009
     *
1010
     * @param bool $isLabelAsterisked
1011
     *
1012
     * @return $this
1013
     */
1014
    public function required($isLabelAsterisked = true)
1015
    {
1016
        if ($isLabelAsterisked) {
1017
            $this->setLabelClass(['asterisk']);
1018
        }
1019
1020
        return $this->attribute('required', true);
1021
    }
1022
1023
    /**
1024
     * Set the field automatically get focus.
1025
     *
1026
     * @return $this
1027
     */
1028
    public function autofocus()
1029
    {
1030
        return $this->attribute('autofocus', true);
1031
    }
1032
1033
    /**
1034
     * Set the field as readonly mode.
1035
     *
1036
     * @return $this
1037
     */
1038
    public function readonly()
1039
    {
1040
        return $this->attribute('readonly', true);
1041
    }
1042
1043
    /**
1044
     * Set field as disabled.
1045
     *
1046
     * @return $this
1047
     */
1048
    public function disable()
1049
    {
1050
        return $this->attribute('disabled', true);
1051
    }
1052
1053
    /**
1054
     * Set field placeholder.
1055
     *
1056
     * @param string $placeholder
1057
     *
1058
     * @return $this
1059
     */
1060
    public function placeholder($placeholder = '')
1061
    {
1062
        $this->placeholder = $placeholder;
1063
1064
        return $this;
1065
    }
1066
1067
    /**
1068
     * Get placeholder.
1069
     *
1070
     * @return string
1071
     */
1072
    public function getPlaceholder()
1073
    {
1074
        return $this->placeholder ?: trans('admin.input').' '.$this->label;
1075
    }
1076
1077
    /**
1078
     * Prepare for a field value before update or insert.
1079
     *
1080
     * @param $value
1081
     *
1082
     * @return mixed
1083
     */
1084
    public function prepare($value)
1085
    {
1086
        return $value;
1087
    }
1088
1089
    /**
1090
     * Format the field attributes.
1091
     *
1092
     * @return string
1093
     */
1094
    protected function formatAttributes()
1095
    {
1096
        $html = [];
1097
1098
        foreach ($this->attributes as $name => $value) {
1099
            $html[] = $name.'="'.e($value).'"';
1100
        }
1101
1102
        return implode(' ', $html);
1103
    }
1104
1105
    /**
1106
     * @return $this
1107
     */
1108
    public function disableHorizontal()
1109
    {
1110
        $this->horizontal = false;
1111
1112
        return $this;
1113
    }
1114
1115
    /**
1116
     * @return array
1117
     */
1118
    public function getViewElementClasses()
1119
    {
1120
        if ($this->horizontal) {
1121
            return [
1122
                'label'      => "col-sm-{$this->width['label']} {$this->getLabelClass()}",
1123
                'field'      => "col-sm-{$this->width['field']}",
1124
                'form-group' => $this->getGroupClass(true),
1125
            ];
1126
        }
1127
1128
        return ['label' => "{$this->getLabelClass()}", 'field' => '', 'form-group' => ''];
1129
    }
1130
1131
    /**
1132
     * Set form element class.
1133
     *
1134
     * @param string|array $class
1135
     *
1136
     * @return $this
1137
     */
1138
    public function setElementClass($class)
1139
    {
1140
        $this->elementClass = array_merge($this->elementClass, (array) $class);
1141
1142
        return $this;
1143
    }
1144
1145
    /**
1146
     * Get element class.
1147
     *
1148
     * @return array
1149
     */
1150
    protected function getElementClass()
1151
    {
1152
        if (!$this->elementClass) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->elementClass of type array 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...
1153
            $name = $this->elementName ?: $this->formatName($this->column);
0 ignored issues
show
Bug introduced by
It seems like $this->column can also be of type array; however, Encore\Admin\Form\Field::formatName() 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...
1154
1155
            $this->elementClass = (array) str_replace(['[', ']'], '_', $name);
1156
        }
1157
1158
        return $this->elementClass;
1159
    }
1160
1161
    /**
1162
     * Get element class string.
1163
     *
1164
     * @return mixed
1165
     */
1166 View Code Duplication
    protected function getElementClassString()
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...
1167
    {
1168
        $elementClass = $this->getElementClass();
1169
1170
        if (Arr::isAssoc($elementClass)) {
1171
            $classes = [];
1172
1173
            foreach ($elementClass as $index => $class) {
1174
                $classes[$index] = is_array($class) ? implode(' ', $class) : $class;
1175
            }
1176
1177
            return $classes;
1178
        }
1179
1180
        return implode(' ', $elementClass);
1181
    }
1182
1183
    /**
1184
     * Get element class selector.
1185
     *
1186
     * @return string|array
1187
     */
1188 View Code Duplication
    protected function getElementClassSelector()
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...
1189
    {
1190
        $elementClass = $this->getElementClass();
1191
1192
        if (Arr::isAssoc($elementClass)) {
1193
            $classes = [];
1194
1195
            foreach ($elementClass as $index => $class) {
1196
                $classes[$index] = '.'.(is_array($class) ? implode('.', $class) : $class);
1197
            }
1198
1199
            return $classes;
1200
        }
1201
1202
        return '.'.implode('.', $elementClass);
1203
    }
1204
1205
    /**
1206
     * Add the element class.
1207
     *
1208
     * @param $class
1209
     *
1210
     * @return $this
1211
     */
1212
    public function addElementClass($class)
1213
    {
1214
        if (is_array($class) || is_string($class)) {
1215
            $this->elementClass = array_merge($this->elementClass, (array) $class);
1216
1217
            $this->elementClass = array_unique($this->elementClass);
1218
        }
1219
1220
        return $this;
1221
    }
1222
1223
    /**
1224
     * Remove element class.
1225
     *
1226
     * @param $class
1227
     *
1228
     * @return $this
1229
     */
1230
    public function removeElementClass($class)
1231
    {
1232
        $delClass = [];
1233
1234
        if (is_string($class) || is_array($class)) {
1235
            $delClass = (array) $class;
1236
        }
1237
1238
        foreach ($delClass as $del) {
1239
            if (($key = array_search($del, $this->elementClass)) !== false) {
1240
                unset($this->elementClass[$key]);
1241
            }
1242
        }
1243
1244
        return $this;
1245
    }
1246
1247
    /**
1248
     * Set form group class.
1249
     *
1250
     * @param string|array $class
1251
     *
1252
     * @return $this
1253
     */
1254
    public function setGroupClass($class)
1255
    : self
1256
    {
1257
        if (is_array($class)) {
1258
            $this->groupClass = array_merge($this->groupClass, $class);
1259
        } else {
1260
            array_push($this->groupClass, $class);
1261
        }
1262
1263
        return $this;
1264
    }
1265
1266
    /**
1267
     * Get element class.
1268
     *
1269
     * @param bool $default
1270
     *
1271
     * @return string
1272
     */
1273
    protected function getGroupClass($default = false)
1274
    : string
1275
    {
1276
        return ($default ? 'form-group ' : '').implode(' ', array_filter($this->groupClass));
1277
    }
1278
1279
    /**
1280
     * reset field className.
1281
     *
1282
     * @param string $className
1283
     * @param string $resetClassName
1284
     *
1285
     * @return $this
1286
     */
1287
    public function resetElementClassName(string $className, string $resetClassName)
1288
    {
1289
        if (($key = array_search($className, $this->getElementClass())) !== false) {
1290
            $this->elementClass[$key] = $resetClassName;
1291
        }
1292
1293
        return $this;
1294
    }
1295
1296
    /**
1297
     * Add variables to field view.
1298
     *
1299
     * @param array $variables
1300
     *
1301
     * @return $this
1302
     */
1303
    protected function addVariables(array $variables = [])
1304
    {
1305
        $this->variables = array_merge($this->variables, $variables);
1306
1307
        return $this;
1308
    }
1309
1310
    /**
1311
     * @return string
1312
     */
1313
    public function getLabelClass()
1314
    : string
1315
    {
1316
        return implode(' ', $this->labelClass);
1317
    }
1318
1319
    /**
1320
     * @param array $labelClass
1321
     *
1322
     * @return self
1323
     */
1324
    public function setLabelClass(array $labelClass)
1325
    : self
1326
    {
1327
        $this->labelClass = $labelClass;
1328
1329
        return $this;
1330
    }
1331
1332
    /**
1333
     * Get the view variables of this field.
1334
     *
1335
     * @return array
1336
     */
1337
    public function variables()
1338
    {
1339
        return array_merge($this->variables, [
1340
            'id'          => $this->id,
1341
            'name'        => $this->elementName ?: $this->formatName($this->column),
0 ignored issues
show
Bug introduced by
It seems like $this->column can also be of type array; however, Encore\Admin\Form\Field::formatName() 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...
1342
            'help'        => $this->help,
1343
            'class'       => $this->getElementClassString(),
1344
            'value'       => $this->value(),
1345
            'label'       => $this->label,
1346
            'viewClass'   => $this->getViewElementClasses(),
1347
            'column'      => $this->column,
1348
            'errorKey'    => $this->getErrorKey(),
1349
            'attributes'  => $this->formatAttributes(),
1350
            'placeholder' => $this->getPlaceholder(),
1351
        ]);
1352
    }
1353
1354
    /**
1355
     * Get view of this field.
1356
     *
1357
     * @return string
1358
     */
1359
    public function getView()
1360
    {
1361
        if (!empty($this->view)) {
1362
            return $this->view;
1363
        }
1364
1365
        $class = explode('\\', get_called_class());
1366
1367
        return 'admin::form.'.strtolower(end($class));
1368
    }
1369
1370
    /**
1371
     * Set view of current field.
1372
     *
1373
     * @param string $view
1374
     *
1375
     * @return string
1376
     */
1377
    public function setView($view)
1378
    {
1379
        $this->view = $view;
1380
1381
        return $this;
1382
    }
1383
1384
    /**
1385
     * Get script of current field.
1386
     *
1387
     * @return string
1388
     */
1389
    public function getScript()
1390
    {
1391
        return $this->script;
1392
    }
1393
1394
    /**
1395
     * Set script of current field.
1396
     *
1397
     * @param string $script
1398
     *
1399
     * @return $this
1400
     */
1401
    public function setScript($script)
1402
    {
1403
        $this->script = $script;
1404
1405
        return $this;
1406
    }
1407
1408
    /**
1409
     * To set this field should render or not.
1410
     *
1411
     * @param bool $display
1412
     *
1413
     * @return $this
1414
     */
1415
    public function setDisplay(bool $display)
1416
    {
1417
        $this->display = $display;
1418
1419
        return $this;
1420
    }
1421
1422
    /**
1423
     * If this field should render.
1424
     *
1425
     * @return bool
1426
     */
1427
    protected function shouldRender()
1428
    {
1429
        if (!$this->display) {
1430
            return false;
1431
        }
1432
1433
        return true;
1434
    }
1435
1436
    /**
1437
     * @param \Closure $callback
1438
     *
1439
     * @return \Encore\Admin\Form\Field
1440
     */
1441
    public function with(Closure $callback)
1442
    {
1443
        $this->callback = $callback;
1444
1445
        return $this;
1446
    }
1447
1448
    /**
1449
     * Render this filed.
1450
     *
1451
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|string
1452
     */
1453
    public function render()
1454
    {
1455
        if (!$this->shouldRender()) {
1456
            return '';
1457
        }
1458
1459
        if ($this->callback instanceof Closure) {
1460
            $this->value = $this->callback->call($this->form->model(), $this->value, $this);
1461
        }
1462
1463
        $this->addRequiredAttributeFromRules();
1464
1465
        Admin::script($this->script);
1466
1467
        return view($this->getView(), $this->variables());
0 ignored issues
show
Bug Compatibility introduced by
The expression view($this->getView(), $this->variables()); of type Illuminate\View\View|Ill...\Contracts\View\Factory adds the type Illuminate\Contracts\View\Factory to the return on line 1467 which is incompatible with the return type declared by the interface Illuminate\Contracts\Support\Renderable::render of type string.
Loading history...
1468
    }
1469
1470
    /**
1471
     * @return string
1472
     */
1473
    public function __toString()
1474
    {
1475
        return $this->render()->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...
1476
    }
1477
}
1478