FormSelect::__construct()   A
last analyzed

Complexity

Conditions 5
Paths 6

Size

Total Lines 31
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 31
rs 9.5222
cc 5
nc 6
nop 9

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
3
namespace ProtoneMedia\LaravelFormComponents\Components;
4
5
use Illuminate\Contracts\Support\Arrayable;
6
use Illuminate\Support\Arr;
7
use Illuminate\Support\Str;
8
9
class FormSelect extends Component
10
{
11
    use HandlesValidationErrors;
12
    use HandlesBoundValues;
13
14
    public string $name;
15
    public string $label;
16
    public $options;
17
    public $selectedKey;
18
    public bool $multiple;
19
    public bool $floating;
20
21
    /**
22
     * Create a new component instance.
23
     *
24
     * @return void
25
     */
26
    public function __construct(
27
        string $name,
28
        string $label = '',
29
        $options = [],
30
        $bind = null,
31
        $default = null,
32
        bool $multiple = false,
33
        bool $showErrors = true,
34
        bool $manyRelation = false,
35
        bool $floating = false
36
    ) {
37
        $this->name         = $name;
38
        $this->label        = $label;
39
        $this->options      = $options;
40
        $this->manyRelation = $manyRelation;
41
42
        if ($this->isNotWired()) {
43
            $inputName = Str::before($name, '[]');
44
45
            $default = $this->getBoundValue($bind, $inputName) ?: $default;
46
47
            $this->selectedKey = old(static::convertBracketsToDots($inputName), $default);
48
49
            if ($this->selectedKey instanceof Arrayable) {
50
                $this->selectedKey = $this->selectedKey->toArray();
51
            }
52
        }
53
54
        $this->multiple   = $multiple;
55
        $this->showErrors = $showErrors;
56
        $this->floating   = $floating && !$multiple;
57
    }
58
59
    public function isSelected($key): bool
60
    {
61
        if ($this->isWired()) {
62
            return false;
63
        }
64
65
        return in_array($key, Arr::wrap($this->selectedKey));
66
    }
67
}
68