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