Completed
Pull Request — development (#586)
by
unknown
02:25
created

Select_Field::set_has_ui()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 5
ccs 0
cts 3
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Carbon_Fields\Field;
4
5
use Carbon_Fields\Helper\Helper;
6
7
/**
8
 * Select dropdown field class.
9
 */
10
class Select_Field extends Predefined_Options_Field {
11
	/**
12
	 * Sets either the select has a nice UI
13
	 *
14
	 * @var        boolean
15
	 */
16
	protected $has_ui = false;
17
18
	public function set_has_ui( $state ) {
19
		$this->has_ui = (bool) $state;
20
21
		return $this;
22
	}
23
24
	/**
25
	 * {@inheritDoc}
26
	 */
27
	public function set_value_from_input( $input ) {
28
		$options_values = $this->get_options_values();
29
30
		$value = null;
31
		if ( isset( $input[ $this->get_name() ] ) ) {
32
			$raw_value = stripslashes_deep( $input[ $this->get_name() ] );
33
			$raw_value = Helper::get_valid_options( array( $raw_value ), $options_values );
34
			if ( ! empty( $raw_value ) ) {
35
				$value = $raw_value[0];
36
			}
37
		}
38
39
		if ( $value === null ) {
40
			$value = $options_values[0];
41
		}
42
43
		return $this->set_value( $value );
44
	}
45
46
	/**
47
	 * {@inheritDoc}
48
	 */
49 View Code Duplication
	public function to_json( $load ) {
50
		$field_data = parent::to_json( $load );
51
52
		$options = $this->parse_options( $this->get_options(), true );
53
		$value   = strval( $this->get_formatted_value() );
54
55
		$field_data = array_merge(
56
			$field_data,
57
			array(
58
				'value'   => strval( $value ),
59
				'options' => $options,
60
				'has_ui'  => $this->has_ui,
61
			)
62
		);
63
64
		return $field_data;
65
	}
66
67
	/**
68
	 * {@inheritDoc}
69
	 */
70
	public function get_formatted_value() {
71
		$options_values = $this->get_options_values();
72
		if ( empty( $options_values ) ) {
73
			$options_values[] = '';
74
		}
75
76
		$value = $this->get_value();
77
		$value = $this->get_values_from_options( array( $value ) );
78
		$value = ! empty( $value ) ? $value[0] : $options_values[0];
79
80
		return $value;
81
	}
82
}
83