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