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

Kirki_Modules_PostMessage::script_var_dimensions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 3
rs 10
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 field.
63
	 *
64
	 * @access protected
65
	 * @since 3.0.0
66
	 * @param array $args The arguments.
67
	 */
68
	protected function script( $args ) {
69
70
		$script = 'wp.customize(\'' . $args['settings'] . '\',function(value){value.bind(function(newval){';
71
		// append unique style tag if not exist
72
		// The style ID.
73
		$style_id = 'kirki-postmessage-' . str_replace( array( '[', ']' ), '', $args['settings'] );
74
		$script .= 'if(!jQuery(\'' . $style_id . '\').size()){jQuery(\'head\').append(\'<style id="' . $style_id . '"></style>\');}';
75
76
		// Loop through the js_vars and generate the script.
77
		foreach ( $args['js_vars'] as $key => $js_var ) {
78
			$js_var['index_key'] = $key;
79
			$func_name = 'script_var_' . str_replace( array( 'kirki-', '-' ), array( '', '_' ), $args['type'] );
80
			if ( method_exists( $this, $func_name ) ) {
81
				$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...
82
				continue;
83
			}
84
			$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...
85
		}
86
		$combo_extra_script = '';
87
		$combo_css_script   = '';
88
		foreach ( $field['scripts'] as $script_array ) {
89
			$combo_extra_script .= $script_array['script'];
90
			$combo_css_script   .= $script_array['css'];
91
		}
92
		$text = ( 'css' === $combo_css_script ) ? 'css' : '\'' . $combo_css_script . '\'';
93
		$script .= $combo_extra_script . 'jQuery(\'#' . $style_id . '\').text(' . $text . ');';
94
		$script .= '});});';
95
		return $script;
96
	}
97
98
	/**
99
	 * Generates script for a single js_var.
100
	 *
101
	 * @access protected
102
	 * @since 3.0.0
103
	 * @param array $args  The arguments for this js_var.
104
	 */
105
	protected function script_var( $args ) {
106
		$script = '';
107
		$property_script = '';
108
109
		$value_key = 'newval' . $args['index_key'];
110
		$property_script .= $value_key . '=newval;';
111
112
		$args = $this->get_args( $args );
113
114
		// Apply callback to the value if a callback is defined.
115
		if ( ! empty( $args['js_callback'][0] ) ) {
116
			$script .= $value_key . '=' . $args['js_callback'][0] . '(' . $value_key . ',' . $args['js_callback'][1] . ');';
117
		}
118
119
		// Apply the value_pattern.
120
		if ( '' !== $args['value_pattern'] ) {
121
			$script .= $this->value_pattern_replacements( $value_key, $args );
122
		}
123
124
		// Tweak to add url() for background-images.
125
		if ( 'background-image' === $args['property'] ) {
126
			$script .= 'if(-1===' . $value_key . '.indexOf(\'url(\')){' . $value_key . '=\'url("\'+' . $value_key . '+\'");}';
127
		}
128
129
		// Apply prefix.
130
		$value = $value_key;
131
		if ( '' !== $args['prefix'] ) {
132
			$value = $args['prefix'] . '+' . $value_key;
133
		}
134
135
		return array(
136
			'script' => $property_script . $script,
137
			'css'    => $args['element'] . '{' . $args['property'] . ':\'+' . $value . '+\'' . $args['units'] . $args['suffix'] . ';}',
138
		);
139
	}
140
141
	/**
142
	 * Processes script generation for fields that save an array.
143
	 *
144
	 * @access protected
145
	 * @since 3.0.0
146
	 * @param array $args  The arguments for this js_var.
147
	 */
148
	protected function script_var_array( $args ) {
149
150
		$script = 'css=\'\';';
151
		$property_script = '';
152
153
		$value_key = 'newval' . $args['index_key'];
154
		$property_script .= $value_key . '=newval;';
155
156
		$args = $this->get_args( $args );
157
158
		// Apply callback to the value if a callback is defined.
159
		if ( ! empty( $args['js_callback'][0] ) ) {
160
			$script .= $value_key . '=' . $args['js_callback'][0] . '(' . $value_key . ',' . $args['js_callback'][1] . ');';
161
		}
162
		$script .= '_.each(' . $value_key . ', function(subValue,subKey){';
163
164
		// Apply the value_pattern.
165
		if ( '' !== $args['value_pattern'] ) {
166
			$script .= $this->value_pattern_replacements( 'subValue', $args );
167
		}
168
169
		// Tweak to add url() for background-images.
170
		if ( 'background-image' === $args['property'] ) {
171
			$script .= 'if(-1===subValue.indexOf(\'url(\')){subValue=\'url("\'+subValue+\'");}';
172
		}
173
174
		// Apply prefix.
175
		$value = $value_key;
176
		if ( '' !== $args['prefix'] ) {
177
			$value = '\'' . $args['prefix'] . '\'+subValue';
178
		}
179
180
		// Allows us to apply this just for a specific choice in the array of the values.
181
		$script .= 'if(!_.isUndefined(' . $value_key . '.choice)){if(' . $value_key . '.choice===subKey){';
182
		$script .= 'css+=\'' . $args['element'] . '{' . $args['property'] . ':\'+subValue+\';}\';';
183
		$script .= '}}else{';
184
185
		// Mostly used for padding, margin & position properties.
186
		$script .= 'if(_.contains([\'top\',\'bottom\',\'left\',\'right\'],subKey)){';
187
		$script .= 'css+=\'' . $args['element'] . '{' . $args['property'] . '-\'+subKey+\':\'+subValue+\'' . $args['units'] . $args['suffix'] . ';}\';';
188
		$script .= '}else{';
189
190
		// This is where most object-based fields will go.
191
		$script .= 'css+=\'' . $args['element'] . '{\'+subKey+\':\'+subValue+\'' . $args['units'] . $args['suffix'] . ';}\';';
192
		$script .= '}}';
193
		$script .= '});';
194
195
		return array(
196
			'script' => $property_script . $script,
197
			'css'    => 'css',
198
		);
199
	}
200
201
	/**
202
	 * Processes values for dimensions fields.
203
	 *
204
	 * @access protected
205
	 * @since 3.0.0
206
	 * @param array $args  The arguments for this js_var.
207
	 * @param array $field The whole field arguments.
208
	 */
209
	protected function script_var_dimensions( $args, $field ) {
210
		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...
211
	}
212
213
	/**
214
	 * Sanitizes the arguments and makes sure they are all there.
215
	 *
216
	 * @access private
217
	 * @since 3.0.0
218
	 * @param array $args The arguments.
219
	 * @return array
220
	 */
221
	private function get_args( $args ) {
222
223
		// Make sure everything is defined to avoid "undefined index" errors.
224
		$args = wp_parse_args( $args, array(
225
			'element'       => '',
226
			'property'      => '',
227
			'prefix'        => '',
228
			'suffix'        => '',
229
			'units'         => '',
230
			'js_callback'   => array( '', '' ),
231
			'value_pattern' => '',
232
		));
233
234
		// Element should be a string.
235
		if ( is_array( $args['element'] ) ) {
236
			$args['element'] = implode( ',', $args['element'] );
237
		}
238
239
		// Make sure arguments that are passed-on to callbacks are strings.
240
		if ( is_array( $args['js_callback'] ) && isset( $args['js_callback'][1] ) && is_array( $args['js_callback'][1] ) ) {
241
			$args['js_callback'][1] = wp_json_encode( $args['js_callback'][1] );
242
		}
243
		return $args;
244
245
	}
246
247
	/**
248
	 * Returns script for value_pattern & replacements.
249
	 *
250
	 * @access private
251
	 * @since 3.0.0
252
	 * @param string $value   The value placeholder.
253
	 * @param array  $js_vars The js_vars argument.
254
	 * @return string         The script.
255
	 */
256
	private function value_pattern_replacements( $value, $js_vars ) {
257
		$script = '';
258
		$alias  = $value;
259
		if ( isset( $js_vars['replacements'] ) ) {
260
			$script .= 'settings=window.wp.customize.get();';
261
			foreach ( $js_vars['replacements'] as $search => $replace ) {
262
				$replace = '\'+settings["' . $replace . '"]+\'';
263
				$value = str_replace( $search, $replace, $js_vars['value_pattern'] );
264
				$value = trim( $value, '+' );
265
			}
266
		}
267
		$value_compiled = str_replace( '$', '\'+' . $alias . '+\'', $value );
268
		$value_compiled = trim( $value_compiled, '+' );
269
		return $script . $alias . '=\'' . $value_compiled . '\';';
270
	}
271
}
272