Completed
Pull Request — develop (#1334)
by Aristeides
02:53
created

Kirki_Modules_PostMessage::script_var_array()   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 43
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 26
nc 8
nop 1
dl 0
loc 43
rs 8.5806
c 0
b 0
f 0
1
<?php
2
/**
3
 * Automatic postMessage scripts calculation for Kirki controls.
4
 *
5
 * @package     Kirki
6
 * @category    Modules
7
 * @author      Aristeides Stathopoulos
8
 * @copyright   Copyright (c) 2017, Aristeides Stathopoulos
9
 * @license     http://opensource.org/licenses/https://opensource.org/licenses/MIT
10
 * @since       3.0.0
11
 */
12
13
// Exit if accessed directly.
14
if ( ! defined( 'ABSPATH' ) ) {
15
	exit;
16
}
17
18
/**
19
 * Adds styles to the customizer.
20
 */
21
class Kirki_Modules_PostMessage {
22
23
	/**
24
	 * The script.
25
	 *
26
	 * @access protected
27
	 * @since 3.0.0
28
	 * @var string
29
	 */
30
	protected $script = '';
31
32
	/**
33
	 * Constructor.
34
	 *
35
	 * @access public
36
	 * @since 3.0.0
37
	 */
38
	public function __construct() {
39
		add_action( 'customize_preview_init', array( $this, 'postmessage' ) );
40
	}
41
42
	/**
43
	 * Enqueues the postMessage script
44
	 * and adds variables to it using the wp_localize_script function.
45
	 * The rest is handled via JS.
46
	 */
47
	public function postmessage() {
48
49
		wp_enqueue_script( 'kirki_auto_postmessage', trailingslashit( Kirki::$url ) . 'modules/postmessage/postmessage.js', array( 'jquery', 'customize-preview' ), false, true );
50
		$fields = Kirki::$fields;
51
		foreach ( $fields as $field ) {
52
			if ( isset( $field['transport'] ) && 'postMessage' === $field['transport'] && isset( $field['js_vars'] ) && ! empty( $field['js_vars'] ) && is_array( $field['js_vars'] ) && isset( $field['settings'] ) ) {
53
				$this->script .= $this->script( $field );
54
			}
55
		}
56
		$this->script = apply_filters( 'kirki/postmessage/script', $this->script );
57
		wp_add_inline_script( 'kirki_auto_postmessage', $this->script, 'after' );
58
59
	}
60
61
	/**
62
	 * Generates script for a single js_var.
63
	 *
64
	 * @access protected
65
	 * @since 3.0.0
66
	 * @param array $args  The arguments for this js_var.
67
	 */
68
	protected function script_var( $args ) {
69
		$script = '';
70
		$property_script = '';
71
72
		$value_key = 'newval' . $args['index_key'];
73
		$property_script .= $value_key . '=newval;';
74
75
		$args = $this->get_args( $args );
76
77
		// Apply callback to the value if a callback is defined.
78
		if ( ! empty( $args['js_callback'][0] ) ) {
79
			$script .= $value_key . '=' . $args['js_callback'][0] . '(' . $value_key . ',' . $args['js_callback'][1] . ');';
80
		}
81
82
		// Apply the value_pattern.
83
		if ( '' !== $args['value_pattern'] ) {
84
			$script .= $this->value_pattern_replacements( $value_key, $args );
85
		}
86
87
		// Apply prefix, units, suffix.
88
		$value = $value_key;
89
		if ( '' !== $args['prefix'] ) {
90
			$value = $args['prefix'] . '+' . $value_key;
91
		}
92
		return array(
93
			'script' => $property_script . $script,
94
			'css'    => $args['element'] . '{' . $args['property'] . ':\'+' . $value . '+\'' . $args['units'] . $args['suffix'] . ';}',
95
		);
96
	}
97
98
	/**
99
	 * Generates script for a single field.
100
	 *
101
	 * @access protected
102
	 * @since 3.0.0
103
	 * @param array $args The arguments.
104
	 */
105
	protected function script( $args ) {
106
107
		$script = 'wp.customize(\'' . $args['settings'] . '\',function(value){value.bind(function(newval){';
108
		// append unique style tag if not exist
109
		// The style ID.
110
		$style_id = 'kirki-postmessage-' . str_replace( array( '[', ']' ), '', $args['settings'] );
111
		$script .= 'if(!jQuery(\'' . $style_id . '\').size()){jQuery(\'head\').append(\'<style id="' . $style_id . '"></style>\');}';
112
113
		// Loop through the js_vars and generate the script.
114
		foreach ( $args['js_vars'] as $key => $js_var ) {
115
			$js_var['index_key'] = $key;
116
			$func_name = 'script_var_' . str_replace( array( 'kirki-', '-' ), array( '', '_' ), $args['type'] );
117
			if ( method_exists( $this, $func_name ) ) {
118
				$field['scripts'][ $key ] = call_user_func_array( array( $this, $func_name ), array( $js_var, $args ) );
0 ignored issues
show
Coding Style Comprehensibility introduced by
$field was never initialized. Although not strictly required by PHP, it is generally a good practice to add $field = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
119
				continue;
120
			}
121
			$field['scripts'][ $key ] = $this->script_var( $js_var, $args );
0 ignored issues
show
Bug introduced by
The variable $field does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Unused Code introduced by
The call to Kirki_Modules_PostMessage::script_var() has too many arguments starting with $args.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
122
		}
123
		$combo_extra_script = '';
124
		$combo_css_script   = '';
125
		foreach ( $field['scripts'] as $script_array ) {
126
			$combo_extra_script .= $script_array['script'];
127
			$combo_css_script   .= $script_array['css'];
128
		}
129
		$text = ( 'css' === $combo_css_script ) ? 'css' : '\'' . $combo_css_script . '\'';
130
		$script .= $combo_extra_script . 'jQuery(\'#' . $style_id . '\').text(' . $text . ');';
131
		$script .= '});});';
132
		return $script;
133
	}
134
135
	/**
136
	 * Processes values for dimensions fields.
137
	 *
138
	 * @access protected
139
	 * @since 3.0.0
140
	 * @param array $args  The arguments for this js_var.
141
	 * @param array $field The whole field arguments.
142
	 */
143
	protected function script_var_dimensions( $args, $field ) {
144
		return $this->script_var_array( $args, $field );
0 ignored issues
show
Unused Code introduced by
The call to Kirki_Modules_PostMessage::script_var_array() has too many arguments starting with $field.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
145
	}
146
147
	/**
148
	 * Processes script generation for fields that save an array.
149
	 *
150
	 * @access protected
151
	 * @since 3.0.0
152
	 * @param array $args  The arguments for this js_var.
153
	 */
154
	protected function script_var_array( $args ) {
155
156
		$script = 'css=\'\';';
157
		$property_script = '';
158
159
		$value_key = 'newval' . $args['index_key'];
160
		$property_script .= $value_key . '=newval;';
161
162
		$args = $this->get_args( $args );
163
164
		// Apply callback to the value if a callback is defined.
165
		if ( ! empty( $args['js_callback'][0] ) ) {
166
			$script .= $value_key . '=' . $args['js_callback'][0] . '(' . $value_key . ',' . $args['js_callback'][1] . ');';
167
		}
168
		$script .= '_.each(' . $value_key . ', function(subValue,subKey){';
169
		// Apply the value_pattern.
170
		if ( '' !== $args['value_pattern'] ) {
171
			$script .= $this->value_pattern_replacements( 'subValue', $args );
172
		}
173
		// Apply prefix, units, suffix.
174
		$value = $value_key;
175
		if ( '' !== $args['prefix'] ) {
176
			$value = '\'' . $args['prefix'] . '\'+subValue';
177
		}
178
		$script .= 'if(!_.isUndefined(' . $value_key . '.choice)){if(' . $value_key . '.choice===subKey){';
179
		$script .= 'css+=\'' . $args['element'] . '{' . $args['property'] . ':\'+subValue+\';}\';';
180
		$script .= '}}else{';
181
182
		// Mostly used for padding, margin & position properties.
183
		$script .= 'if(_.contains([\'top\',\'bottom\',\'left\',\'right\'],subKey)){';
184
		$script .= 'css+=\'' . $args['element'] . '{' . $args['property'] . '-\'+subKey+\':\'+subValue+\'' . $args['units'] . $args['suffix'] . ';}\';';
185
		$script .= '}else{';
186
187
		// This is where most object-based fields will go.
188
		$script .= 'css+=\'' . $args['element'] . '{\'+subKey+\':\'+subValue+\'' . $args['units'] . $args['suffix'] . ';}\';';
189
		$script .= '}}';
190
		$script .= '});';
191
192
		return array(
193
			'script' => $property_script . $script,
194
			'css'    => 'css',
195
		);
196
	}
197
198
	/**
199
	 * Sanitizes the arguments and makes sure they are all there.
200
	 *
201
	 * @access private
202
	 * @since 3.0.0
203
	 * @param array $args The arguments.
204
	 * @return array
205
	 */
206
	private function get_args( $args ) {
207
208
		// Make sure everything is defined to avoid "undefined index" errors.
209
		$args = wp_parse_args( $args, array(
210
			'element'       => '',
211
			'property'      => '',
212
			'prefix'        => '',
213
			'suffix'        => '',
214
			'units'         => '',
215
			'js_callback'   => array( '', '' ),
216
			'value_pattern' => '',
217
		));
218
219
		// Element should be a string.
220
		if ( is_array( $args['element'] ) ) {
221
			$args['element'] = implode( ',', $args['element'] );
222
		}
223
224
		// Make sure arguments that are passed-on to callbacks are strings.
225
		if ( is_array( $args['js_callback'] ) && isset( $args['js_callback'][1] ) && is_array( $args['js_callback'][1] ) ) {
226
			$args['js_callback'][1] = wp_json_encode( $args['js_callback'][1] );
227
		}
228
		return $args;
229
230
	}
231
232
	/**
233
	 * Returns script for value_pattern & replacements.
234
	 *
235
	 * @access private
236
	 * @since 3.0.0
237
	 * @param string $value   The value placeholder.
238
	 * @param array  $js_vars The js_vars argument.
239
	 * @return string         The script.
240
	 */
241
	private function value_pattern_replacements( $value, $js_vars ) {
242
		$script = '';
243
		$alias  = $value;
244
		if ( isset( $js_vars['replacements'] ) ) {
245
			$script .= 'settings=window.wp.customize.get();';
246
			foreach ( $js_vars['replacements'] as $search => $replace ) {
247
				$replace = '\'+settings["' . $replace . '"]+\'';
248
				$value = str_replace( $search, $replace, $js_vars['value_pattern'] );
249
				$value = trim( $value, '+' );
250
			}
251
		}
252
		$value_compiled = str_replace( '$', '\'+' . $alias . '+\'', $value );
253
		$value_compiled = trim( $value_compiled, '+' );
254
		return $script . $alias . '=\'' . $value_compiled . '\';';
255
	}
256
}
257