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

Select_Field   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 73
Duplicated Lines 19.18 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
dl 14
loc 73
ccs 0
cts 32
cp 0
rs 10
c 0
b 0
f 0
wmc 9
lcom 1
cbo 2

4 Methods

Rating   Name   Duplication   Size   Complexity  
A set_has_ui() 0 5 1
A set_value_from_input() 0 18 4
A to_json() 14 17 1
A get_formatted_value() 0 12 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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