Passed
Push — master ( 5f6e57...34e66c )
by Sergei
05:58 queued 03:17
created

AbstractToggleWidget::withToggle()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

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