Checkbox.php
3 days ago
Input.php
3 days ago
MultiSelect.php
3 days ago
Radio.php
3 days ago
Select.php
3 days ago
Select.php
101 lines
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace AC\Form\Element; |
| 6 | |
| 7 | use AC\Form\Element; |
| 8 | |
| 9 | class Select extends Element |
| 10 | { |
| 11 | protected string $no_result = ''; |
| 12 | |
| 13 | protected function render_options(array $options): string |
| 14 | { |
| 15 | $output = []; |
| 16 | |
| 17 | foreach ($options as $key => $option) { |
| 18 | if (isset($option['options']) && is_array($option['options'])) { |
| 19 | $output[] = $this->render_optgroup($option); |
| 20 | |
| 21 | continue; |
| 22 | } |
| 23 | |
| 24 | $output[] = $this->render_option((string)$key, (string)$option); |
| 25 | } |
| 26 | |
| 27 | return implode("\n", $output); |
| 28 | } |
| 29 | |
| 30 | protected function render_option(string $key, string $label): string |
| 31 | { |
| 32 | $template = '<option %s>%s</option>'; |
| 33 | $attributes = $this->get_option_attributes($key); |
| 34 | |
| 35 | return sprintf($template, $this->get_attributes_as_string($attributes), esc_html($label)); |
| 36 | } |
| 37 | |
| 38 | protected function get_option_attributes(string $key): array |
| 39 | { |
| 40 | $attributes = []; |
| 41 | $attributes['value'] = $key; |
| 42 | |
| 43 | if ($this->selected($key)) { |
| 44 | $attributes['selected'] = 'selected'; |
| 45 | } |
| 46 | |
| 47 | return $attributes; |
| 48 | } |
| 49 | |
| 50 | protected function selected(string $value): bool |
| 51 | { |
| 52 | return (bool)selected($this->get_value(), $value, false); |
| 53 | } |
| 54 | |
| 55 | protected function render_optgroup(array $group): string |
| 56 | { |
| 57 | $template = '<optgroup %s>%s</optgroup>'; |
| 58 | $attributes = []; |
| 59 | |
| 60 | if (isset($group['title'])) { |
| 61 | $attributes['label'] = esc_attr($group['title']); |
| 62 | } |
| 63 | |
| 64 | return sprintf( |
| 65 | $template, |
| 66 | $this->get_attributes_as_string($attributes), |
| 67 | $this->render_options($group['options']) |
| 68 | ); |
| 69 | } |
| 70 | |
| 71 | public function render(): string |
| 72 | { |
| 73 | if (! $this->get_options() && $this->get_no_result()) { |
| 74 | return $this->get_no_result(); |
| 75 | } |
| 76 | |
| 77 | $template = ' |
| 78 | <select %s> |
| 79 | %s |
| 80 | </select> |
| 81 | %s'; |
| 82 | |
| 83 | $attributes = $this->get_attributes(); |
| 84 | $attributes['name'] = $this->get_name(); |
| 85 | $attributes['id'] = $this->get_id(); |
| 86 | |
| 87 | return sprintf( |
| 88 | $template, |
| 89 | $this->get_attributes_as_string($attributes), |
| 90 | $this->render_options($this->get_options()), |
| 91 | $this->render_description() |
| 92 | ); |
| 93 | } |
| 94 | |
| 95 | public function get_no_result(): string |
| 96 | { |
| 97 | return $this->no_result; |
| 98 | } |
| 99 | |
| 100 | } |
| 101 |