Completed
Push — develop ( d93c9f...50fc22 )
by Aristeides
03:11
created

sanitize_repeater_setting()   C

Complexity

Conditions 7
Paths 48

Size

Total Lines 24
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 12
nc 48
nop 1
dl 0
loc 24
rs 6.7272
c 0
b 0
f 0
1
<?php
2
/**
3
 * Repeater Customizer Setting.
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.0
10
 */
11
12
// Exit if accessed directly.
13
if ( ! defined( 'ABSPATH' ) ) {
14
	exit;
15
}
16
17
/**
18
 * Repeater Settings.
19
 */
20
class Kirki_Settings_Repeater_Setting extends WP_Customize_Setting {
21
22
	/**
23
	 * Constructor.
24
	 *
25
	 * Any supplied $args override class property defaults.
26
	 *
27
	 * @access public
28
	 * @param WP_Customize_Manager $manager The WordPress WP_Customize_Manager object.
29
	 * @param string               $id       A specific ID of the setting. Can be a theme mod or option name.
30
	 * @param array                $args     Setting arguments.
31
	 */
32
	public function __construct( $manager, $id, $args = array() ) {
33
		parent::__construct( $manager, $id, $args );
34
35
		// Will onvert the setting from JSON to array. Must be triggered very soon.
36
		add_filter( "customize_sanitize_{$this->id}", array( $this, 'sanitize_repeater_setting' ), 10, 1 );
37
	}
38
39
	/**
40
	 * Fetch the value of the setting.
41
	 *
42
	 * @access public
43
	 * @return mixed The value.
44
	 */
45
	public function value() {
46
		$value = parent::value();
47
		if ( ! is_array( $value ) ) {
48
					$value = array();
49
		}
50
51
		return $value;
52
	}
53
54
	/**
55
	 * Convert the JSON encoded setting coming from Customizer to an Array.
56
	 *
57
	 * @access public
58
	 * @param string $value URL Encoded JSON Value.
59
	 * @return array
60
	 */
61
	public function sanitize_repeater_setting( $value ) {
62
63
		if ( ! is_array( $value ) ) {
64
			$value = json_decode( urldecode( $value ) );
65
		}
66
		$sanitized = ( empty( $value ) || ! is_array( $value ) ) ? array() : $value;
67
68
		// Make sure that every row is an array, not an object.
69
		foreach ( $sanitized as $key => $_value ) {
70
			if ( empty( $_value ) ) {
71
				unset( $sanitized[ $key ] );
72
			} else {
73
				$sanitized[ $key ] = (array) $_value;
74
			}
75
		}
76
77
		// Reindex array.
78
		if ( is_array( $sanitized ) ) {
79
			$sanitized = array_values( $sanitized );
80
		}
81
82
		return $sanitized;
83
84
	}
85
}
86