Debian Codegraph @

vendor/ipl/html/src/FormElement/SelectElement.php

raw
1 <?php
2
3 namespace ipl\Html\FormElement;
4
5 use ipl\Html\Attributes;
6 use ipl\Html\Common\MultipleAttribute;
7 use ipl\Html\Html;
8 use ipl\Html\HtmlElement;
9 use ipl\Validator\DeferredInArrayValidator;
10 use ipl\Validator\ValidatorChain;
11 use UnexpectedValueException;
12
13 class SelectElement extends BaseFormElement
14 {
15 use MultipleAttribute;
16
17 protected $tag = 'select';
18
19 /** @var SelectOption[] */
20 protected $options = [];
21
22 /** @var SelectOption[]|HtmlElement[] */
23 protected $optionContent = [];
24
25 /** @var array Disabled select options */
26 protected $disabledOptions = [];
27
28 /** @var array|string|null */
29 protected $value;
30
31 /** @var bool Whether to prepend a disabled "Please choose" option */
32 protected bool $pleaseChoose = false;
33
34 /**
35 * Set whether to prepend a disabled "Please choose" option
36 *
37 * When enabled, a disabled option with an empty value and the label
38 * " - Please choose - " is prepended to the rendered options.
39 *
40 * @param bool $pleaseChoose
41 *
42 * @return $this
43 */
44 public function setPleaseChoose(bool $pleaseChoose): self
45 {
46 $this->pleaseChoose = $pleaseChoose;
47
48 return $this;
49 }
50
51 /**
52 * Get the option with specified value
53 *
54 * @param string|int $value
55 *
56 * @return ?SelectOption
57 */
58 public function getOption(string|int $value): ?SelectOption
59 {
60 return $this->options[$value] ?? null;
61 }
62
63 /**
64 * Set the options from specified values
65 *
66 * @param array $options
67 *
68 * @return $this
69 */
70 public function setOptions(array $options): self
71 {
72 $this->options = [];
73 $this->optionContent = [];
74 foreach ($options as $value => $label) {
75 $this->optionContent[$value] = $this->makeOption($value, $label);
76 }
77
78 return $this;
79 }
80
81 /**
82 * Set the specified options as disable
83 *
84 * @param array $disabledOptions
85 *
86 * @return $this
87 */
88 public function setDisabledOptions(array $disabledOptions): self
89 {
90 if (! empty($this->options)) {
91 foreach ($this->options as $option) {
92 $optionValue = $option->getValue();
93
94 $option->setAttribute(
95 'disabled',
96 in_array($optionValue, $disabledOptions, ! is_int($optionValue))
97 || ($optionValue === '' && in_array(null, $disabledOptions, true))
98 );
99 }
100
101 $this->disabledOptions = [];
102 } else {
103 $this->disabledOptions = $disabledOptions;
104 }
105
106 return $this;
107 }
108
109 /**
110 * Get the value of the element
111 *
112 * Returns `array` when the attribute `multiple` is set to `true`, `string` or `null` otherwise
113 *
114 * @return array|string|null
115 */
116 public function getValue()
117 {
118 if ($this->isMultiple()) {
119 return parent::getValue() ?? [];
120 }
121
122 return parent::getValue();
123 }
124
125 public function getValueAttribute()
126 {
127 // select elements don't have a value attribute
128 return null;
129 }
130
131 public function getNameAttribute()
132 {
133 $name = $this->getName();
134
135 return $this->isMultiple() ? ($name . '[]') : $name;
136 }
137
138 /**
139 * Make the selectOption for the specified value and the label
140 *
141 * @param string|int $value Value of the option
142 * @param string|array $label Label of the option
143 *
144 * @return SelectOption|HtmlElement
145 */
146 protected function makeOption(string|int $value, string|array $label)
147 {
148 if (is_array($label)) {
149 $grp = Html::tag('optgroup', ['label' => $value]);
150 foreach ($label as $option => $val) {
151 $grp->addHtml($this->makeOption($option, $val));
152 }
153
154 return $grp;
155 }
156
157 $option = (new SelectOption($value, $label))
158 ->setAttribute('disabled', in_array($value, $this->disabledOptions, ! is_int($value)));
159
160 $option->getAttributes()->registerAttributeCallback('selected', function () use ($option) {
161 return $this->isSelectedOption($option->getValue());
162 });
163
164 $this->options[$value] = $option;
165
166 return $this->options[$value];
167 }
168
169 /**
170 * Get whether the given option is selected
171 *
172 * @param string|int $optionValue
173 *
174 * @return bool
175 */
176 protected function isSelectedOption(string|int $optionValue): bool
177 {
178 $value = $this->getValue();
179
180 if ($this->isMultiple()) {
181 if (! is_array($value)) {
182 throw new UnexpectedValueException(
183 'Value must be an array when the `multiple` attribute is set to `true`'
184 );
185 }
186
187 return in_array($optionValue, $value, ! is_int($optionValue))
188 || ($optionValue === '' && in_array(null, $value, true));
189 }
190
191 if (is_array($value)) {
192 throw new UnexpectedValueException(
193 'Value cannot be an array without setting the `multiple` attribute to `true`'
194 );
195 }
196
197 if ($optionValue === '' && $value === null) {
198 return true;
199 }
200
201 return is_int($optionValue)
202 // The loose comparison is required because PHP casts
203 // numeric strings to integers if used as array keys
204 ? $value == $optionValue
205 : $value === $optionValue;
206 }
207
208 protected function addDefaultValidators(ValidatorChain $chain): void
209 {
210 $chain->add(
211 new DeferredInArrayValidator(function (): array {
212 $possibleValues = [];
213
214 foreach ($this->options as $option) {
215 if ($option->getAttributes()->get('disabled')->getValue()) {
216 continue;
217 }
218
219 $possibleValues[] = $option->getValue();
220 }
221
222 return $possibleValues;
223 })
224 );
225 }
226
227 protected function assemble()
228 {
229 if ($this->pleaseChoose && ! isset($this->optionContent[''])) {
230 $option = (new SelectOption('', sprintf(' - %s - ', $this->translate('Please choose'))))
231 ->setAttribute('disabled', true);
232 $option->getAttributes()->registerAttributeCallback('selected', fn() => $this->isSelectedOption(''));
233 $this->options[''] = $option;
234 $this->addHtml($option);
235 }
236
237 $this->addHtml(...array_values($this->optionContent));
238 }
239
240 protected function registerAttributeCallbacks(Attributes $attributes)
241 {
242 parent::registerAttributeCallbacks($attributes);
243
244 $attributes->registerAttributeCallback(
245 'options',
246 null,
247 [$this, 'setOptions']
248 );
249
250 $attributes->registerAttributeCallback(
251 'disabledOptions',
252 null,
253 [$this, 'setDisabledOptions']
254 );
255
256 $attributes->registerAttributeCallback('pleaseChoose', null, $this->setPleaseChoose(...));
257
258 // ZF1 compatibility:
259 $this->getAttributes()->registerAttributeCallback(
260 'multiOptions',
261 null,
262 [$this, 'setOptions']
263 );
264
265 $this->registerMultipleAttributeCallback($attributes);
266 }
267 }