<?php namespace PHPFUI\Input; class Select extends \PHPFUI\Input\Input implements \Countable { protected array $labelClass = []; protected array $options = []; public function __construct(string $name, string $label = '') { parent::__construct('text', $name, $label); } public function addLabelClass(string $class) : static { $this->labelClass[] = $class; return $this; } public function addOptGroup(\PHPFUI\Input\OptGroup $group) : static { $this->options[] = $group; return $this; } public function addOption(string $label, ?string $value = null, bool $selected = false, bool $disabled = false) : static { if (null === $value) { $value = $label; } $label = '' === $label ? ' ' : \PHPFUI\TextHelper::htmlentities($label); $this->options[] = ['label' => $label, 'value' => (string)$value, 'selected' => $selected ? ' selected' : '', 'disabled' => $disabled ? ' disabled' : '', ]; return $this; } public function count() : int { return \count($this->options); } public function removeAll() : static { $this->options = []; return $this; } public function removeOption(string $value) : bool { foreach ($this->options as $key => $select) { if ($select['value'] == $value) { unset($this->options[$key]); return true; } } return false; } public function select(string $selection) : static { foreach ($this->options as &$values) { $values['selected'] = $values['value'] == $selection ? ' selected' : ''; } return $this; } protected function getEnd() : string { return $this->getHint() ?? ''; } protected function getStart() : string { $label = $error = ''; if ($this->label) { $label = new \PHPFUI\HTML5Element('label'); foreach ($this->labelClass as $class) { $label->addClass($class); } $label->setAttribute('for', $this->getId()); $label->add($this->getToolTip($this->label)); } else { $label = new \PHPFUI\Container(); } if ($this->required) { $this->addErrorMessage(\PHPFUI\Language::$selectError); $label->add(\PHPFUI\Language::$required); $this->setAttribute('required'); } if ($this->errorMessages) { $error = new \PHPFUI\HTML5Element('span'); $error->add(\implode('', $this->errorMessages)); $error->addClass('form-error'); $this->setAttribute('aria-errormessage', $error->getId()); } $class = $this->getClass(); $attributes = $this->getAttributes(); $id = $this->getIdAttribute(); $label->add("<select{$id}{$class}{$attributes} name='{$this->getName()}'>"); foreach ($this->options as $option) { if (\is_object($option)) { $label->add($option); } else { $selected = $option['selected']; $disabled = $option['disabled']; $label->add("<option value='{$option['value']}'{$selected}{$disabled}>{$option['label']}</option>"); } } $label->add('</select>'); $label->add($error); return $label; } }