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

Multiselect_Field::to_json()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 16
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 23
rs 9.0856
1
<?php
2
3
namespace Carbon_Fields\Field;
4
5
use Carbon_Fields\Helper\Delimiter;
6
use Carbon_Fields\Helper\Helper;
7
use Carbon_Fields\Value_Set\Value_Set;
8
9
/**
10
 * Multiselect field class.
11
 * Allows to create a select where multiple values can be selected.
12
 */
13
class Multiselect_Field extends Predefined_Options_Field {
14
	/**
15
	 * Default field value
16
	 *
17
	 * @var array
18
	 */
19
	protected $default_value = array();
20
21
	/**
22
	 * Value delimiter
23
	 *
24
	 * @var string
25
	 */
26
	protected $value_delimiter = '|';
27
28
	/**
29
	 * Create a field from a certain type with the specified label.
30
	 *
31
	 * @param string $type  Field type
32
	 * @param string $name  Field name
33
	 * @param string $label Field label
34
	 */
35
	public function __construct( $type, $name, $label ) {
36
		$this->set_value_set( new Value_Set( Value_Set::TYPE_MULTIPLE_VALUES ) );
37
		parent::__construct( $type, $name, $label );
38
	}
39
40
	/**
41
	 * {@inheritDoc}
42
	 */
43
	public function set_value_from_input( $input ) {
44
		if ( ! isset( $input[ $this->get_name() ] ) ) {
45
			return $this->set_value( array() );
46
		}
47
48
		$value_delimiter = $this->value_delimiter;
49
		$options_values = $this->get_options_values();
50
51
		$value = stripslashes_deep( $input[ $this->get_name() ] );
52
		$value = Delimiter::split( $value, $this->value_delimiter );
53
		$value = array_map( function( $val ) use ( $value_delimiter ) {
54
			return Delimiter::unquote( $val, $value_delimiter );
55
		}, $value );
56
		$value = Helper::get_valid_options( $value, $options_values );
57
58
		return $this->set_value( $value );
59
	}
60
61
	/**
62
	 * {@inheritDoc}
63
	 */
64
	public function to_json( $load ) {
65
		$field_data = parent::to_json( $load );
66
67
		$value_delimiter = $this->value_delimiter;
68
69
		$options = $this->parse_options( $this->get_options(), true );
70
		$options = array_map( function( $option ) use ( $value_delimiter ) {
71
			$option['value'] = Delimiter::quote( $option['value'], $value_delimiter );
72
			return $option;
73
		}, $options );
74
75
		$value = array_map( function( $value ) use ( $value_delimiter ) {
76
			return Delimiter::quote( $value, $value_delimiter );
77
		}, $this->get_formatted_value() );
78
79
		$field_data = array_merge( $field_data, array(
80
			'options' => $options,
81
			'value' => $value,
82
			'valueDelimiter' => $this->value_delimiter,
83
		) );
84
85
		return $field_data;
86
	}
87
88
	/**
89
	 * {@inheritDoc}
90
	 */
91
	public function get_formatted_value() {
92
		$value = $this->get_value();
93
		$value = $this->get_values_from_options( $value );
94
		return $value;
95
	}
96
}
97