Passed
Push — master ( d3891b...901043 )
by Alexander
02:19
created

Widget::addOptions()   A

Complexity

Conditions 5
Paths 12

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 5.0144

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 11
c 1
b 0
f 0
nc 12
nop 2
dl 0
loc 22
ccs 11
cts 12
cp 0.9167
crap 5.0144
rs 9.6111
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Bulma;
6
7
use Yiisoft\Html\Html;
8
use Yiisoft\Widget\Widget as BaseWidget;
9
10
use function strpos;
11
12
abstract class Widget extends BaseWidget
13
{
14
    private ?string $id = null;
15
    private bool $autoGenerate = true;
16
    private string $autoIdPrefix = 'w';
17
    private static int $counter = 0;
18
19
    /**
20
     * Set the Id of the widget.
21
     *
22
     * @param string $value
23
     *
24
     * @return static
25
     */
26 1
    public function id(string $value): self
27
    {
28 1
        $new = clone $this;
29 1
        $new->id = $value;
30 1
        return $new;
31
    }
32
33
    /**
34
     * Counter used to generate {@see id} for widgets.
35
     *
36
     * @param int $value
37
     */
38 81
    public static function counter(int $value): void
39
    {
40 81
        self::$counter = $value;
41 81
    }
42
43
    /**
44
     * The prefix to the automatically generated widget IDs.
45
     *
46
     * @param string $value
47
     *
48
     * @return static
49
     *
50
     * {@see getId()}
51
     */
52 1
    public function autoIdPrefix(string $value): self
53
    {
54 1
        $new = clone $this;
55 1
        $new->autoIdPrefix = $value;
56 1
        return $new;
57
    }
58
59
    /**
60
     * Returns the Id of the widget.
61
     *
62
     * @return string|null Id of the widget.
63
     */
64 51
    protected function getId(): ?string
65
    {
66 51
        if ($this->autoGenerate && $this->id === null) {
67 50
            $this->id = $this->autoIdPrefix . ++self::$counter;
68
        }
69
70 51
        return $this->id;
71
    }
72
73
    /**
74
     * Validate CSS class default options.
75
     *
76
     * @param array $options
77
     * @param string $defaultClass
78
     *
79
     * @return array
80
     */
81 70
    protected function addOptions(array $options, string $defaultClass): array
82
    {
83 70
        $class = '';
84
85 70
        if (isset($options['class'])) {
86 16
            $class = $options['class'];
87 16
            unset($options['class']);
88 16
            if (is_array($class)) {
89
                $class = implode(' ', $class);
90
            }
91
        }
92
93
        /** @psalm-var string $class */
94 70
        if (strpos($class, $defaultClass) === false) {
95 70
            Html::addCssClass($options, $defaultClass);
96
        }
97
98 70
        if (!empty($class)) {
99 16
            Html::addCssClass($options, $class);
100
        }
101
102 70
        return $options;
103
    }
104
}
105