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