AbstractToggleWidget   A
last analyzed

Complexity

Total Complexity 14

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 33
c 1
b 0
f 0
dl 0
loc 68
ccs 34
cts 34
cp 1
rs 10
wmc 14

5 Methods

Rating   Name   Duplication   Size   Complexity  
B prepareToggleOptions() 0 24 9
A withToggle() 0 10 2
A withToggleLabel() 0 6 1
A renderToggle() 0 6 1
A withToggleOptions() 0 6 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Bootstrap5;
6
7
use Stringable;
8
use Yiisoft\Arrays\ArrayHelper;
9
use Yiisoft\Html\Html;
10
use Yiisoft\Html\Tag\Base\Tag;
11
12
abstract class AbstractToggleWidget extends Widget
13
{
14
    protected array $toggleOptions = [];
15
    protected string|Stringable $toggleLabel = '';
16
    protected bool $renderToggle = true;
17
18
    abstract protected function toggleComponent(): string;
19
20 46
    public function withToggleOptions(array $options): static
21
    {
22 46
        $new = clone $this;
23 46
        $new->toggleOptions = $options;
24
25 46
        return $new;
26
    }
27
28 66
    public function withToggleLabel(string|Stringable $label): static
29
    {
30 66
        $new = clone $this;
31 66
        $new->toggleLabel = $label;
32
33 66
        return $new;
34
    }
35
36 41
    public function withToggle(bool $value): static
37
    {
38 41
        if ($this->renderToggle === $value) {
39 21
            return $this;
40
        }
41
42 20
        $new = clone $this;
43 20
        $new->renderToggle = $value;
44
45 20
        return $new;
46
    }
47
48 76
    protected function prepareToggleOptions(): array
49
    {
50 76
        $options = $this->toggleOptions;
51 76
        $tagName = ArrayHelper::remove($options, 'tag', 'button');
52 76
        $encode = ArrayHelper::remove($options, 'encode', true);
53 76
        $options['data-bs-toggle'] = $this->toggleComponent();
54
55 76
        if (!isset($options['aria-controls']) && !isset($options['aria']['controls'])) {
56 75
            $options['aria-controls'] = $this->getId();
57
        }
58
59 76
        if ($tagName !== 'button') {
60 3
            $options['role'] = 'button';
61 74
        } elseif (!isset($options['type'])) {
62 74
            $options['type'] = 'button';
63
        }
64
65 76
        if ($tagName === 'a' && !isset($options['href'])) {
66 3
            $options['href'] = '#' . $this->getId();
67 74
        } elseif (!isset($options['data-bs-target']) && !isset($options['data']['bs-target'])) {
68 73
            $options['data-bs-target'] = '#' . $this->getId();
69
        }
70
71 76
        return [$tagName, $options, $encode];
72
    }
73
74 76
    public function renderToggle(): Tag
75
    {
76 76
        [$tagName, $options, $encode] = $this->prepareToggleOptions();
77
78 76
        return Html::tag($tagName, $this->toggleLabel, $options)
79 76
            ->encode($encode);
80
    }
81
}
82