Completed
Pull Request — master (#1592)
by Aristeides
04:14 queued 02:08
created

Kirki_Field_Number::set_choices()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 12
nc 2
nop 0
dl 0
loc 18
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * Override field methods
4
 *
5
 * @package     Kirki
6
 * @subpackage  Controls
7
 * @copyright   Copyright (c) 2017, Aristeides Stathopoulos
8
 * @license     http://opensource.org/licenses/https://opensource.org/licenses/MIT
9
 * @since       2.2.7
10
 */
11
12
/**
13
 * Field overrides.
14
 */
15
class Kirki_Field_Number extends Kirki_Field {
16
17
	/**
18
	 * Sets the control type.
19
	 *
20
	 * @access protected
21
	 */
22
	protected function set_type() {
23
24
		$this->type = 'kirki-number';
25
26
	}
27
28
	/**
29
	 * Sets the $sanitize_callback
30
	 *
31
	 * @access protected
32
	 */
33
	protected function set_sanitize_callback() {
34
35
		$this->sanitize_callback = array( $this, 'sanitize' );
36
37
	}
38
39
	/**
40
	 * Sets the $choices
41
	 *
42
	 * @access protected
43
	 */
44
	protected function set_choices() {
45
46
		if ( ! is_customize_preview() ) {
47
			return;
48
		}
49
		$this->choices = wp_parse_args(
50
			$this->choices,
51
			array(
52
				'min'  => -999999999,
53
				'max'  => 999999999,
54
				'step' => 1,
55
			)
56
		);
57
		// Make sure min, max & step are all numeric.
58
		$this->choices['min']  = filter_var( $this->choices['min'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION );
59
		$this->choices['max']  = filter_var( $this->choices['max'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION );
60
		$this->choices['step'] = filter_var( $this->choices['step'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION );
61
	}
62
63
	/**
64
	 * Sanitizes numeric values.
65
	 *
66
	 * @access public
67
	 * @param integer|string $value The checkbox value.
68
	 * @return bool
69
	 */
70
	public function sanitize( $value = 0 ) {
71
72
		$this->set_choices();
73
74
		$value = filter_var( $value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION );
75
76
		// Minimum & maximum value limits.
77
		if ( $value < $this->choices['min'] || $value > $this->choices['max'] ) {
78
			return max( min( $value, $this->choices['max'] ), $this->choices['min'] );
79
		}
80
81
		// Only multiple of steps.
82
		$steps = ( $value - $this->choices['min'] ) / $this->choices['step'];
83
		if ( ! is_int( $steps ) ) {
84
			$value = $this->choices['min'] + ( round( $steps ) * $this->choices['step'] );
85
		}
86
		return $value;
87
	}
88
}
89