Passed
Pull Request — master (#127)
by
unknown
02:59
created

AbstractToggleWidget::prepareToggleOptions()   B

Complexity

Conditions 9
Paths 18

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 9

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 9
eloc 15
c 1
b 0
f 0
nc 18
nop 0
dl 0
loc 24
ccs 16
cts 16
cp 1
crap 9
rs 8.0555
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 bsToggle(): string;
19
20 45
    public function withToggleOptions(array $options): static
21
    {
22 45
        $new = clone $this;
23 45
        $new->toggleOptions = $options;
24
25 45
        return $new;
26
    }
27
28 58
    public function withToggleLabel(string|Stringable $label): static
29
    {
30 58
        $new = clone $this;
31 58
        $new->toggleLabel = $label;
32
33 58
        return $new;
34
    }
35
36 39
    public function withToggle(bool $value): static
37
    {
38 39
        if ($this->renderToggle === $value) {
39 21
            return $this;
40
        }
41
42 18
        $new = clone $this;
43 18
        $new->renderToggle = $value;
44
45 18
        return $new;
46
    }
47
48 66
    protected function prepareToggleOptions(): array
49
    {
50 66
        $options = $this->toggleOptions;
51 66
        $tagName = ArrayHelper::remove($options, 'tag', 'button');
52 66
        $encode = ArrayHelper::remove($options, 'encode', true);
53 66
        $options['data-bs-toggle'] = $this->bsToggle();
54
55 66
        if (!isset($options['aria-controls']) && !isset($options['aria']['controls'])) {
56 65
            $options['aria-controls'] = $this->getId();
57
        }
58
59 66
        if ($tagName !== 'button') {
60 3
            $options['role'] = 'button';
61 64
        } elseif (!isset($options['type'])) {
62 64
            $options['type'] = 'button';
63
        }
64
65 66
        if ($tagName === 'a' && !isset($options['href'])) {
66 3
            $options['href'] = '#' . $this->getId();
67 64
        } elseif (!isset($options['data-bs-target']) && !isset($options['data']['bs-target'])) {
68 63
            $options['data-bs-target'] = '#' . $this->getId();
69
        }
70
71 66
        return [$tagName, $options, $encode];
72
    }
73
74 66
    public function renderToggle(): Tag
75
    {
76 66
        list($tagName, $options, $encode) = $this->prepareToggleOptions();
77
78 66
        return Html::tag($tagName, $this->toggleLabel, $options)
79 66
            ->encode($encode);
80
    }
81
}
82