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

Select_Field::set_value_from_input()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
nc 6
nop 1
dl 0
loc 18
rs 9.6666
c 0
b 0
f 0
ccs 0
cts 11
cp 0
crap 20
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( $field_data, array(
56
			'value' => strval( $value ),
57
			'options' => $options,
58
			'has_ui' => $this->has_ui,
59
		) );
60
61
		return $field_data;
62
	}
63
64
	/**
65
	 * {@inheritDoc}
66
	 */
67
	public function get_formatted_value() {
68
		$options_values = $this->get_options_values();
69
		if ( empty( $options_values ) ) {
70
			$options_values[] = '';
71
		}
72
73
		$value = $this->get_value();
74
		$value = $this->get_values_from_options( array( $value ) );
75
		$value = ! empty( $value ) ? $value[0] : $options_values[0];
76
77
		return $value;
78
	}
79
}
80