Completed
Push — development ( 9a304e...c8ad86 )
by
unknown
02:20
created

Checkbox_Field::get_formatted_value()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Carbon_Fields\Field;
4
5
/**
6
 * Single checkbox field class.
7
 */
8
class Checkbox_Field extends Field {
9
10
	/**
11
	 * @{inheritDoc}
12
	 */
13
	protected $default_value = false;
14
15
	/**
16
	 * The value that is saved in the database when
17
	 * this checkbox field is enabled.
18
	 *
19
	 * @var string
20
	 */
21
	protected $option_value = 'yes';
22
23
	/**
24
	 * Get the option value.
25
	 *
26
	 * @return string
27
	 */
28
	public function get_option_value() {
29
		return $this->option_value;
30
	}
31
32
	/**
33
	 * Set the option value.
34
	 *
35
	 * @param  string $value New value
36
	 * @return Field  $this
37
	 */
38
	public function set_option_value( $value ) {
39
		$this->option_value = $value;
40
		return $this;
41
	}
42
43
	/**
44
	 * {@inheritDoc}
45
	 */
46
	public function set_value_from_input( $input ) {
47
		parent::set_value_from_input( $input );
48
		if ( $this->get_value() !== $this->get_option_value() ) {
49
			$this->set_value( '' );
50
		}
51
		return $this;
52
	}
53
54
	/**
55
	 * {@inheritDoc}
56
	 */
57
	public function set_value( $value ) {
58
		if ( is_bool( $value ) ) {
59
			$value = $value ? $this->get_option_value() : '';
60
		}
61
		return parent::set_value( $value );
62
	}
63
64
	/**
65
	 * Return a differently formatted value for end-users
66
	 *
67
	 * @return mixed
68
	 */
69
	public function get_formatted_value() {
70
		return ( $this->get_value() === $this->get_option_value() );
71
	}
72
73
	/**
74
	 * Returns an array that holds the field data, suitable for JSON representation.
75
	 * In addition to default data, option value and label are added.
76
	 *
77
	 * @param bool $load  Should the value be loaded from the database or use the value from the current instance.
78
	 * @return array
79
	 */
80
	public function to_json( $load ) {
81
		$field_data = parent::to_json( $load );
82
83
		$field_data = array_merge( $field_data, array(
84
			'option_value' => $this->get_option_value(),
85
			'option_label' => parent::get_label(),
86
		) );
87
88
		return $field_data;
89
	}
90
91
	/**
92
	 * Get the field label.
93
	 * Label here is empty because it is displayed in the front-end.
94
	 *
95
	 * @return string Label of the field.
96
	 */
97
	public function get_label() {
98
		return '';
99
	}
100
}
101