Test Failed
Pull Request — master (#127)
by
unknown
13:20
created

AbstractToggleWidget   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 32
c 1
b 0
f 0
dl 0
loc 65
rs 10
wmc 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A prepareToggleOptions() 0 21 5
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
    private array $toggleOptions = [];
15
    private string|Stringable $toggleLabel = '';
16
    protected bool $renderToggle = true;
17
18
    abstract protected function bsToggle(): string;
19
20
    public function withToggleOptions(array $options): static
21
    {
22
        $new = clone $this;
23
        $new->toggleOptions = $options;
24
25
        return $new;
26
    }
27
28
    public function withToggleLabel(string|Stringable $label): static
29
    {
30
        $new = clone $this;
31
        $new->toggleLabel = $label;
32
33
        return $new;
34
    }
35
36
    public function withToggle(bool $value): static
37
    {
38
        if ($this->renderToggle === $value) {
39
            return $this;
40
        }
41
42
        $new = clone $this;
43
        $new->renderToggle = $value;
44
45
        return $new;
46
    }
47
48
    protected function prepareToggleOptions(): array
49
    {
50
        $options = $this->toggleOptions;
51
        $tagName = ArrayHelper::remove($options, 'tag', 'button');
52
        $encode = ArrayHelper::remove($options, 'encode', true);
53
        $options['data-bs-toggle'] = $this->bsToggle();
54
        $options['aria-controls'] = $this->getId();
55
56
        if ($tagName !== 'button') {
57
            $options['role'] = 'button';
58
        } elseif (!isset($options['type'])) {
59
            $options['type'] = 'button';
60
        }
61
62
        if ($tagName === 'a' && !isset($options['href'])) {
63
            $options['href'] = '#' . $this->getId();
64
        } else {
65
            $options['data-bs-target'] = '#' . $this->getId();
66
        }
67
68
        return [$tagName, $options, $encode];
69
    }
70
71
    public function renderToggle(): Tag
72
    {
73
        list($tagName, $options, $encode) = $this->prepareToggleOptions();
74
75
        return Html::tag($tagName, $this->toggleLabel, $options)
76
            ->encode($encode);
77
    }
78
}
79