FormCheckbox   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
eloc 23
c 1
b 0
f 0
dl 0
loc 58
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A generateIdByName() 0 3 1
B __construct() 0 32 7
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 FormCheckbox extends Component
10
{
11
    use HandlesValidationErrors;
12
    use HandlesBoundValues;
13
14
    public string $name;
15
    public string $label;
16
    public $value;
17
    public bool $checked = false;
18
19
    /**
20
     * Create a new component instance.
21
     *
22
     * @return void
23
     */
24
    public function __construct(
25
        string $name,
26
        string $label = '',
27
        $value = 1,
28
        $bind = null,
29
        bool $default = false,
30
        bool $showErrors = true
31
    ) {
32
        $this->name       = $name;
33
        $this->label      = $label;
34
        $this->value      = $value;
35
        $this->showErrors = $showErrors;
36
37
        $inputName = Str::before($name, '[]');
38
39
        if ($oldData = old(static::convertBracketsToDots($inputName))) {
40
            $this->checked = in_array($value, Arr::wrap($oldData));
41
        }
42
43
        if (!session()->hasOldInput() && $this->isNotWired()) {
44
            $boundValue = $this->getBoundValue($bind, $inputName);
45
46
            if ($boundValue instanceof Arrayable) {
47
                $boundValue = $boundValue->toArray();
48
            }
49
50
            if (is_array($boundValue)) {
51
                $this->checked = in_array($value, $boundValue);
52
                return;
53
            }
54
55
            $this->checked = is_null($boundValue) ? $default : $boundValue;
56
        }
57
    }
58
59
    /**
60
     * Generates an ID by the name and value attributes.
61
     *
62
     * @return string
63
     */
64
    protected function generateIdByName(): string
65
    {
66
        return "auto_id_" . $this->name . "_" . $this->value;
67
    }
68
}
69