Completed
Push — master ( 361a80...57c765 )
by Atanas
07:10
created

Select_Field   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 56
Duplicated Lines 23.21 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 2 Features 0
Metric Value
c 2
b 2
f 0
dl 13
loc 56
ccs 0
cts 17
cp 0
rs 10
wmc 8
lcom 1
cbo 2

3 Methods

Rating   Name   Duplication   Size   Complexity  
A set_value_from_input() 0 18 4
A to_json() 13 13 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
	 * {@inheritDoc}
13
	 */
14
	public function set_value_from_input( $input ) {
15
		$options_values = $this->get_options_values();
16
17
		$value = null;
18
		if ( isset( $input[ $this->get_name() ] ) ) {
19
			$raw_value = stripslashes_deep( $input[ $this->get_name() ] );
20
			$raw_value = Helper::get_valid_options( array( $raw_value ), $options_values );
21
			if ( ! empty( $raw_value ) ) {
22
				$value = $raw_value[0];
23
			}
24
		}
25
26
		if ( $value === null ) {
27
			$value = $options_values[0];
28
		}
29
30
		return $this->set_value( $value );
31
	}
32
33
	/**
34
	 * {@inheritDoc}
35
	 */
36 View Code Duplication
	public function to_json( $load ) {
37
		$field_data = parent::to_json( $load );
38
39
		$options = $this->parse_options( $this->get_options(), true );
40
		$value = strval( $this->get_formatted_value() );
41
42
		$field_data = array_merge( $field_data, array(
43
			'value' => strval( $value ),
44
			'options' => $options,
45
		) );
46
47
		return $field_data;
48
	}
49
50
	/**
51
	 * {@inheritDoc}
52
	 */
53
	public function get_formatted_value() {
54
		$options_values = $this->get_options_values();
55
		if ( empty( $options_values ) ) {
56
			$options_values[] = '';
57
		}
58
59
		$value = $this->get_value();
60
		$value = $this->get_values_from_options( array( $value ) );
61
		$value = ! empty( $value ) ? $value[0] : $options_values[0];
62
63
		return $value;
64
	}
65
}
66