Completed
Push — milestone/2_0/react-ui ( 21feb1...1c376a )
by
unknown
03:59
created

Text_Field::set_attribute()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 2
eloc 6
nc 2
nop 2
dl 0
loc 8
rs 9.4285
c 1
b 0
f 1
ccs 0
cts 6
cp 0
crap 6
1
<?php
2
3
namespace Carbon_Fields\Field;
4
5
use Carbon_Fields\Exception\Incorrect_Syntax_Exception;
6
7
/**
8
 * Text field class.
9
 */
10
class Text_Field extends Field {
11
	
12
	/**
13
	 * Key-value array of attribtues and their values
14
	 * 
15
	 * @var array
16
	 */
17
	protected $attributes = array(
18
		'type' => 'text',
19
	);
20
21
	/**
22
	 * Array of attributes the user is allowed to change
23
	 * 
24
	 * @var array<string>
25
	 */
26
	protected $allowed_attributes = array( 'max', 'maxlength', 'min', 'pattern', 'placeholder', 'readonly', 'step', 'type' );
27
28
	/**
29
	 * Set attribute and it's value
30
	 * 
31
	 * @param string $name
32
	 * @param string $value
33
	 * @return Field $this
34
	 */
35
	public function set_attribute( $name, $value = '' ) {
36
		if ( ! in_array( $name, $this->allowed_attributes ) ) {
37
			Incorrect_Syntax_Exception::raise( 'Only the following attributes are allowed: ' . implode( ', ', $this->allowed_attributes ) . '.' );
38
			return $this;
39
		}
40
		$this->attributes[ $name ] = $value;
41
		return $this;
42
	}
43
44
	/**
45
	 * Returns an array that holds the field data, suitable for JSON representation.
46
	 * 
47
	 * @param bool $load  Should the value be loaded from the database or use the value from the current instance.
48
	 * @return array
49
	 */
50
	public function to_json( $load ) {
51
		$field_data = parent::to_json( $load );
52
53
		$field_data = array_merge( $field_data, array(
54
			'attributes' => $this->attributes,
55
		) );
56
57
		return $field_data;
58
	}
59
}
60