public static function renderSelectOptions($selection, $items, &$tagOptions = [])
{
$lines = [];
$encodeSpaces = ArrayHelper::remove($tagOptions, 'encodeSpaces', false);
$encode = ArrayHelper::remove($tagOptions, 'encode', true);
if (isset($tagOptions['prompt'])) {
$promptOptions = ['value' => ''];
if (is_string($tagOptions['prompt'])) {
$promptText = $tagOptions['prompt'];
} else {
$promptText = $tagOptions['prompt']['text'];
$promptOptions = array_merge($promptOptions, $tagOptions['prompt']['options']);
}
$promptText = $encode ? static::encode($promptText) : $promptText;
if ($encodeSpaces) {
$promptText = str_replace(' ', ' ', $promptText);
}
$lines[] = static::tag('option', $promptText, $promptOptions);
}
$options = isset($tagOptions['options']) ? $tagOptions['options'] : [];
$groups = isset($tagOptions['groups']) ? $tagOptions['groups'] : [];
unset($tagOptions['prompt'], $tagOptions['options'], $tagOptions['groups']);
$options['encodeSpaces'] = ArrayHelper::getValue($options, 'encodeSpaces', $encodeSpaces);
$options['encode'] = ArrayHelper::getValue($options, 'encode', $encode);
foreach ($items as $key => $value) {
if (is_array($value)) {
$groupAttrs = isset($groups[$key]) ? $groups[$key] : [];
if (!isset($groupAttrs['label'])) {
$groupAttrs['label'] = $key;
}
$attrs = ['options' => $options, 'groups' => $groups, 'encodeSpaces' => $encodeSpaces, 'encode' => $encode];
$content = static::renderSelectOptions($selection, $value, $attrs);
$lines[] = static::tag('optgroup', "\n" . $content . "\n", $groupAttrs);
} else {
$attrs = isset($options[$key]) ? $options[$key] : [];
$attrs['value'] = (string) $key;
if (!array_key_exists('selected', $attrs)) {
$attrs['selected'] = $selection !== null && (!ArrayHelper::isTraversable($selection) && !strcmp($key, $selection) || ArrayHelper::isTraversable($selection) && ArrayHelper::isIn($key, $selection));
}
$text = $encode ? static::encode($value) : $value;
if ($encodeSpaces) {
$text = str_replace(' ', ' ', $text);
}
$lines[] = static::tag('option', $text, $attrs);
}
}
return implode("\n", $lines);
}