-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombo.php
More file actions
78 lines (63 loc) · 1.88 KB
/
Combo.php
File metadata and controls
78 lines (63 loc) · 1.88 KB
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
<?php declare(strict_types=1);
namespace DynamicComponents\AdvancedControls;
use Webmozart\Assert\Assert;
use function array_search;
use function is_string;
class Combo extends \DynamicComponents\Controls\Combo
{
/** @var string[] */
private $options = [];
/**
* @param string[] $options Keys are ignored!
* @param callable|null $onSelected Gets $this as last (only) param
* @param int|string $selected Index or text of option to be selected
*/
public function __construct(array $options, ?callable $onSelected = null, $selected = 0)
{
if (!is_string($selected)) {
Assert::integerish($selected, 'Selected should be either a string or an integer, got %s.');
}
parent::__construct($onSelected);
$this->appendAll($options);
if (!is_string($selected)) {
$this->setSelected((int) $selected);
} else {
$this->setSelectedText($selected);
}
}
public function append(string $text): void
{
parent::append($text);
$this->options[] = $text;
}
/**
* @param string[] $options
*/
public function appendAll(array $options): void
{
foreach ($options as $option) {
$this->append($option);
}
}
/**
* @return string[]
*/
public function getOptions(): array
{
return $this->options;
}
public function getSelectedText(): string
{
return $this->options[$this->getSelected()] ?? '';
}
public function setSelectedText(string $text): void
{
/*
* \UI\Controls\Combo::setSelected() allows any index to be set,
* however non-existing indices will become -1.
*/
$index = array_search($text, $this->options);
$index = $index === false ? -1 : $index;
$this->setSelected($index);
}
}