Passed
Pull Request — master (#192)
by Sergei
07:08 queued 03:58
created

Select   A

Complexity

Total Complexity 25

Size/Duplication

Total Lines 248
Duplicated Lines 0 %

Test Coverage

Coverage 76%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 64
c 1
b 0
f 0
dl 0
loc 248
ccs 57
cts 75
cp 0.76
rs 10
wmc 25

16 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A options() 0 3 1
A optionsData() 0 9 1
A items() 0 5 1
A disabled() 0 5 1
A ariaLabel() 0 5 1
A tabIndex() 0 5 1
A prompt() 0 5 1
A size() 0 5 1
A unselectValue() 0 5 1
A autofocus() 0 5 1
A required() 0 5 1
A promptOption() 0 5 1
B generateInput() 0 33 10
A multiple() 0 5 1
A ariaDescribedBy() 0 5 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Form\Field;
6
7
use InvalidArgumentException;
8
use Stringable;
9
use Yiisoft\Form\Field\Base\InputField;
10
use Yiisoft\Html\Tag\Optgroup;
11
use Yiisoft\Html\Tag\Option;
12
use Yiisoft\Html\Tag\Select as SelectTag;
13
14
/**
15
 * A control for selecting amongst a set of options.
16
 *
17
 * @link https://html.spec.whatwg.org/multipage/form-elements.html#the-select-element
18
 */
19
final class Select extends InputField
20
{
21
    private SelectTag $select;
22
23 5
    public function __construct()
24
    {
25 5
        $this->select = SelectTag::tag();
26
    }
27
28 1
    public function items(Optgroup|Option ...$items): self
29
    {
30 1
        $new = clone $this;
31 1
        $new->select = $this->select->items(...$items);
32 1
        return $new;
33
    }
34
35 1
    public function options(Option ...$options): self
36
    {
37 1
        return $this->items(...$options);
38
    }
39
40
    /**
41
     * @param array $data Options data. The array keys are option values, and the array values are the corresponding
42
     * option labels. The array can also be nested (i.e. some array values are arrays too). For each sub-array,
43
     * an option group will be generated whose label is the key associated with the sub-array.
44
     *
45
     * Example:
46
     * ```php
47
     * [
48
     *     '1' => 'Santiago',
49
     *     '2' => 'Concepcion',
50
     *     '3' => 'Chillan',
51
     *     '4' => 'Moscow'
52
     *     '5' => 'San Petersburg',
53
     *     '6' => 'Novosibirsk',
54
     *     '7' => 'Ekaterinburg'
55
     * ];
56
     * ```
57
     *
58
     * Example with options groups:
59
     * ```php
60
     * [
61
     *     '1' => [
62
     *         '1' => 'Santiago',
63
     *         '2' => 'Concepcion',
64
     *         '3' => 'Chillan',
65
     *     ],
66
     *     '2' => [
67
     *         '4' => 'Moscow',
68
     *         '5' => 'San Petersburg',
69
     *         '6' => 'Novosibirsk',
70
     *         '7' => 'Ekaterinburg'
71
     *     ],
72
     * ];
73
     * ```
74
     * @param bool $encode Whether option content should be HTML-encoded.
75
     * @param array[] $optionsAttributes Array of option attribute sets indexed by option values from {@see $data}.
76
     * @param array[] $groupsAttributes Array of group attribute sets indexed by group labels from {@see $data}.
77
     *
78
     * @psalm-param array<array-key, string|array<array-key,string>> $data
79
     *
80
     * @return self
81
     */
82 5
    public function optionsData(
83
        array $data,
84
        bool $encode = true,
85
        array $optionsAttributes = [],
86
        array $groupsAttributes = []
87
    ): self {
88 5
        $new = clone $this;
89 5
        $new->select = $this->select->optionsData($data, $encode, $optionsAttributes, $groupsAttributes);
90 5
        return $new;
91
    }
92
93
    /**
94
     * @param bool $disabled Whether select input is disabled.
95
     *
96
     * @link https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fe-disabled
97
     */
98 1
    public function disabled(bool $disabled = true): self
99
    {
100 1
        $new = clone $this;
101 1
        $new->inputTagAttributes['disabled'] = $disabled;
102 1
        return $new;
103
    }
104
105
    /**
106
     * Identifies the element (or elements) that describes the object.
107
     *
108
     * @link https://w3c.github.io/aria/#aria-describedby
109
     */
110
    public function ariaDescribedBy(string $value): self
111
    {
112
        $new = clone $this;
113
        $new->inputTagAttributes['aria-describedby'] = $value;
114
        return $new;
115
    }
116
117
    /**
118
     * Defines a string value that labels the current element.
119
     *
120
     * @link https://w3c.github.io/aria/#aria-label
121
     */
122
    public function ariaLabel(string $value): self
123
    {
124
        $new = clone $this;
125
        $new->inputTagAttributes['aria-label'] = $value;
126
        return $new;
127
    }
128
129
    /**
130
     * Focus on the control (put cursor into it) when the page loads. Only one form element could be in focus
131
     * at the same time.
132
     *
133
     * @link https://html.spec.whatwg.org/multipage/interaction.html#attr-fe-autofocus
134
     */
135
    public function autofocus(bool $value = true): self
136
    {
137
        $new = clone $this;
138
        $new->inputTagAttributes['autofocus'] = $value;
139
        return $new;
140
    }
141
142
    /**
143
     * The `tabindex` attribute indicates that its element can be focused, and where it participates in sequential
144
     * keyboard navigation (usually with the Tab key, hence the name).
145
     *
146
     * It accepts an integer as a value, with different results depending on the integer's value:
147
     *
148
     * - A negative value (usually `tabindex="-1"`) means that the element is not reachable via sequential keyboard
149
     *   navigation, but could be focused with Javascript or visually. It's mostly useful to create accessible widgets
150
     *   with JavaScript.
151
     * - `tabindex="0"` means that the element should be focusable in sequential keyboard navigation, but its order is
152
     *   defined by the document's source order.
153
     * - A positive value means the element should be focusable in sequential keyboard navigation, with its order
154
     *   defined by the value of the number. That is, `tabindex="4"` is focused before `tabindex="5"`, but after
155
     *   `tabindex="3"`.
156
     *
157
     * @link https://html.spec.whatwg.org/multipage/interaction.html#attr-tabindex
158
     */
159
    public function tabIndex(?int $value): self
160
    {
161
        $new = clone $this;
162
        $new->inputTagAttributes['tabindex'] = $value;
163
        return $new;
164
    }
165
166
    /**
167
     * @param bool $value Whether the user is to be allowed to select zero or more options.
168
     *
169
     * @link https://html.spec.whatwg.org/multipage/form-elements.html#attr-select-multiple
170
     */
171 2
    public function multiple(bool $value = true): self
172
    {
173 2
        $new = clone $this;
174 2
        $new->inputTagAttributes['multiple'] = $value;
175 2
        return $new;
176
    }
177
178
    /**
179
     * @param string|null $text Text of the option that has dummy value and is rendered as an invitation to select
180
     * a value.
181
     */
182 1
    public function prompt(?string $text): self
183
    {
184 1
        $new = clone $this;
185 1
        $new->select = $this->select->prompt($text);
186 1
        return $new;
187
    }
188
189
    /**
190
     * @param Option|null $option Option that has dummy value and is rendered as an invitation to select a value.
191
     */
192 1
    public function promptOption(?Option $option): self
193
    {
194 1
        $new = clone $this;
195 1
        $new->select = $this->select->promptOption($option);
196 1
        return $new;
197
    }
198
199
    /**
200
     * A boolean attribute. When specified, the element is required.
201
     *
202
     * @param bool $value Whether the control is required for form submission.
203
     *
204
     * @link https://html.spec.whatwg.org/multipage/form-elements.html#attr-select-required
205
     */
206 1
    public function required(bool $value = true): self
207
    {
208 1
        $new = clone $this;
209 1
        $new->inputTagAttributes['required'] = $value;
210 1
        return $new;
211
    }
212
213
    /**
214
     * The size of the control.
215
     *
216
     * @param int $value The number of options to show to the user.
217
     *
218
     * @link https://html.spec.whatwg.org/multipage/form-elements.html#attr-select-size
219
     */
220 1
    public function size(int $value): self
221
    {
222 1
        $new = clone $this;
223 1
        $new->inputTagAttributes['size'] = $value;
224 1
        return $new;
225
    }
226
227 1
    public function unselectValue(bool|float|int|string|Stringable|null $value): self
228
    {
229 1
        $new = clone $this;
230 1
        $new->select = $this->select->unselectValue($value);
231 1
        return $new;
232
    }
233
234 4
    protected function generateInput(): string
235
    {
236 4
        $value = $this->getAttributeValue();
237 4
        $multiple = (bool) ($this->inputTagAttributes['multiple'] ?? false);
238
239 4
        if ($multiple) {
240
            /** @var mixed $value */
241 1
            $value ??= [];
242 1
            if (!is_iterable($value)) {
243
                throw new InvalidArgumentException(
244
                    'Select field with multiple option requires iterable or null value.'
245
                );
246
            }
247
        } else {
248 3
            if (!is_bool($value)
249 3
                && !is_string($value)
250 3
                && !is_numeric($value)
251 3
                && $value !== null
252 3
                && (!is_object($value) || !method_exists($value, '__toString'))
253
            ) {
254
                throw new InvalidArgumentException(
255
                    'Non-multiple Select field requires a string, numeric, bool, Stringable or null value.'
256
                );
257
            }
258 3
            $value = $value === null ? [] : [$value];
259
        }
260
        /** @psalm-var iterable<int, Stringable|scalar> $value */
261
262 4
        return $this->select
263 4
            ->attributes($this->inputTagAttributes)
264 4
            ->name($this->getInputName())
265 4
            ->values($value)
266 4
            ->render();
267
    }
268
}
269