Completed
Push — develop ( b39672...b741d7 )
by Aristeides
11:49 queued 58s
created

Kirki_Modules_PostMessage   D

Complexity

Total Complexity 86

Size/Duplication

Total Lines 454
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 1

Importance

Changes 0
Metric Value
dl 0
loc 454
rs 4.8717
c 0
b 0
f 0
wmc 86
lcom 2
cbo 1

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A get_instance() 0 6 2
B postmessage() 0 13 8
C script() 0 50 10
A script_html_var() 0 9 3
D script_var_typography() 0 46 13
C script_var() 0 38 11
F script_var_array() 0 66 19
A script_var_image_array() 0 7 1
B before_script() 0 28 3
B get_args() 0 25 5
A value_pattern_replacements() 0 15 3
B get_callback() 0 20 7

How to fix   Complexity   

Complex Class

Complex classes like Kirki_Modules_PostMessage often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Kirki_Modules_PostMessage, and based on these observations, apply Extract Interface, too.

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
	 * The object instance.
24
	 *
25
	 * @static
26
	 * @access private
27
	 * @since 3.0.0
28
	 * @var object
29
	 */
30
	private static $instance;
31
32
	/**
33
	 * The script.
34
	 *
35
	 * @access protected
36
	 * @since 3.0.0
37
	 * @var string
38
	 */
39
	protected $script = '';
40
41
	/**
42
	 * Constructor.
43
	 *
44
	 * @access protected
45
	 * @since 3.0.0
46
	 */
47
	protected function __construct() {
48
		add_action( 'customize_preview_init', array( $this, 'postmessage' ) );
49
	}
50
51
	/**
52
	 * Gets an instance of this object.
53
	 * Prevents duplicate instances which avoid artefacts and improves performance.
54
	 *
55
	 * @static
56
	 * @access public
57
	 * @since 3.0.0
58
	 * @return object
59
	 */
60
	public static function get_instance() {
61
		if ( ! self::$instance ) {
62
			self::$instance = new self();
63
		}
64
		return self::$instance;
65
	}
66
67
	/**
68
	 * Enqueues the postMessage script
69
	 * and adds variables to it using the wp_localize_script function.
70
	 * The rest is handled via JS.
71
	 */
72
	public function postmessage() {
73
74
		wp_enqueue_script( 'kirki_auto_postmessage', trailingslashit( Kirki::$url ) . 'modules/postmessage/postmessage.js', array( 'jquery', 'customize-preview' ), false, true );
75
		$fields = Kirki::$fields;
76
		foreach ( $fields as $field ) {
77
			if ( isset( $field['transport'] ) && 'postMessage' === $field['transport'] && isset( $field['js_vars'] ) && ! empty( $field['js_vars'] ) && is_array( $field['js_vars'] ) && isset( $field['settings'] ) ) {
78
				$this->script .= $this->script( $field );
79
			}
80
		}
81
		$this->script = apply_filters( 'kirki/postmessage/script', $this->script );
82
		wp_add_inline_script( 'kirki_auto_postmessage', $this->script, 'after' );
83
84
	}
85
86
	/**
87
	 * Generates script for a single field.
88
	 *
89
	 * @access protected
90
	 * @since 3.0.0
91
	 * @param array $args The arguments.
92
	 */
93
	protected function script( $args ) {
94
95
		$script = 'wp.customize(\'' . $args['settings'] . '\',function(value){value.bind(function(newval){';
96
		// append unique style tag if not exist
97
		// The style ID.
98
		$style_id = 'kirki-postmessage-' . str_replace( array( '[', ']' ), '', $args['settings'] );
99
		$script .= 'if(null===document.getElementById(\'' . $style_id . '\')||\'undefined\'===typeof document.getElementById(\'' . $style_id . '\')){jQuery(\'head\').append(\'<style id="' . $style_id . '"></style>\');}';
100
101
		// Add anything we need before the main script.
102
		$script .= $this->before_script( $args );
103
104
		$field = array(
105
			'scripts' => array(),
106
		);
107
		// Loop through the js_vars and generate the script.
108
		foreach ( $args['js_vars'] as $key => $js_var ) {
109
110
			if ( isset( $js_var['element'] ) ) {
111
				// Array to string.
112
				if ( is_array( $js_var['element'] ) ) {
113
					$js_var['element'] = array_unique( $js_var['element'] );
114
					$js_var['element'] = implode( ',', $js_var['element'] );
115
				}
116
				// Replace single quotes with double quotes to avoid issues with the compiled JS.
117
				$js_var['element'] = str_replace( '\'', '"', $js_var['element'] );
118
			}
119
			if ( isset( $js_var['function'] ) && 'html' === $js_var['function'] ) {
120
				$script .= $this->script_html_var( $js_var );
121
				continue;
122
			}
123
			$js_var['index_key'] = $key;
124
			$callback = $this->get_callback( $args );
125
			if ( is_callable( $callback ) ) {
126
				$field['scripts'][ $key ] = call_user_func_array( $callback, array( $js_var, $args ) );
127
				continue;
128
			}
129
			$field['scripts'][ $key ] = $this->script_var( $js_var );
130
		}
131
		$combo_extra_script = '';
132
		$combo_css_script   = '';
133
		foreach ( $field['scripts'] as $script_array ) {
134
			$combo_extra_script .= $script_array['script'];
135
			$combo_css_script   .= ( 'css' !== $combo_css_script ) ? $script_array['css'] : '';
136
		}
137
		$text = ( 'css' === $combo_css_script ) ? 'css' : '\'' . $combo_css_script . '\'';
138
		$script .= $combo_extra_script . 'jQuery(\'#' . $style_id . '\').text(' . $text . ');';
139
		$script .= 'jQuery(\'#' . $style_id . '\').appendTo(\'head\');';
140
		$script .= '});});';
141
		return $script;
142
	}
143
144
	/**
145
	 * Generates script for a single js_var when using "html" as function.
146
	 *
147
	 * @access protected
148
	 * @since 3.0.0
149
	 * @param array $args  The arguments for this js_var.
150
	 */
151
	protected function script_html_var( $args ) {
152
153
		$script  = ( isset( $args['choice'] ) ) ? 'newval=newval[\'' . $args['choice'] . '\'];' : '';
154
		$script .= 'jQuery(\'' . $args['element'] . '\').html(newval);';
155
		if ( isset( $args['attr'] ) ) {
156
			$script = 'jQuery(\'' . $args['element'] . '\').attr(\'' . $args['attr'] . '\',newval);';
157
		}
158
		return $script;
159
	}
160
161
	/**
162
	 * Generates script for a single js_var.
163
	 *
164
	 * @access protected
165
	 * @since 3.0.0
166
	 * @param array $args  The arguments for this js_var.
167
	 */
168
	protected function script_var( $args ) {
169
		$script = '';
170
		$property_script = '';
171
172
		$value_key = 'newval' . $args['index_key'];
173
		$property_script .= $value_key . '=newval;';
174
175
		$args = $this->get_args( $args );
176
177
		// Apply callback to the value if a callback is defined.
178
		if ( ! empty( $args['js_callback'] ) && is_array( $args['js_callback'] ) && isset( $args['js_callback'][0] ) && ! empty( $args['js_callback'][0] ) ) {
179
			$script .= $value_key . '=' . $args['js_callback'][0] . '(' . $value_key . ',' . $args['js_callback'][1] . ');';
180
		}
181
182
		// Apply the value_pattern.
183
		if ( '' !== $args['value_pattern'] ) {
184
			$script .= $this->value_pattern_replacements( $value_key, $args );
185
		}
186
187
		// Tweak to add url() for background-images.
188
		if ( 'background-image' === $args['property'] && ( ! isset( $args['value_pattern'] ) || false === strpos( $args['value_pattern'], 'gradient' ) ) ) {
189
			$script .= 'if(-1===' . $value_key . '.indexOf(\'url(\')){' . $value_key . '=\'url("\'+' . $value_key . '+\'")\';}';
190
		}
191
192
		// Apply prefix.
193
		$value = $value_key;
194
		if ( '' !== $args['prefix'] ) {
195
			$value = $args['prefix'] . '+' . $value_key;
196
		}
197
		$css = $args['element'] . '{' . $args['property'] . ':\'+' . $value . '+\'' . $args['units'] . $args['suffix'] . ';}';
198
		if ( isset( $args['media_query'] ) ) {
199
			$css = $args['media_query'] . '{' . $css . '}';
200
		}
201
		return array(
202
			'script' => $property_script . $script,
203
			'css'    => $css,
204
		);
205
	}
206
207
	/**
208
	 * Processes script generation for fields that save an array.
209
	 *
210
	 * @access protected
211
	 * @since 3.0.0
212
	 * @param array $args  The arguments for this js_var.
213
	 */
214
	protected function script_var_array( $args ) {
215
216
		$script = ( 0 === $args['index_key'] ) ? 'css=\'\';' : '';
217
		$property_script = '';
218
219
		// Define choice.
220
		$choice  = ( isset( $args['choice'] ) && '' !== $args['choice'] ) ? $args['choice'] : '';
221
222
		$value_key = 'newval' . $args['index_key'];
223
		$property_script .= $value_key . '=newval;';
224
225
		$args = $this->get_args( $args );
226
227
		// Apply callback to the value if a callback is defined.
228
		if ( ! empty( $args['js_callback'] ) && is_array( $args['js_callback'] ) && isset( $args['js_callback'][0] ) && ! empty( $args['js_callback'][0] ) ) {
229
			$script .= $value_key . '=' . $args['js_callback'][0] . '(' . $value_key . ',' . $args['js_callback'][1] . ');';
230
		}
231
		$script .= '_.each(' . $value_key . ', function(subValue,subKey){';
232
233
		// Apply the value_pattern.
234
		if ( '' !== $args['value_pattern'] ) {
235
			$script .= $this->value_pattern_replacements( 'subValue', $args );
236
		}
237
238
		// Tweak to add url() for background-images.
239
		if ( '' === $choice || 'background-image' === $choice ) {
240
			$script .= 'if(\'background-image\'===\'' . $args['property'] . '\'||\'background-image\'===subKey){';
241
			$script .= 'if(-1===subValue.indexOf(\'url(\')){subValue=\'url("\'+subValue+\'")\';}';
242
			$script .= '}';
243
		}
244
245
		// Apply prefix.
246
		$value = $value_key;
247
		if ( '' !== $args['prefix'] ) {
248
			$value = '\'' . $args['prefix'] . '\'+subValue';
249
		}
250
251
		// Mostly used for padding, margin & position properties.
252
		$direction_script  = 'if(_.contains([\'top\',\'bottom\',\'left\',\'right\'],subKey)){';
253
		$direction_script .= 'css+=\'' . $args['element'] . '{' . $args['property'] . '-\'+subKey+\':\'+subValue+\'' . $args['units'] . $args['suffix'] . ';}\';}';
254
		// Allows us to apply this just for a specific choice in the array of the values.
255
		if ( '' !== $choice ) {
256
			$choice_is_direction = ( false !== strpos( $choice, 'top' ) || false !== strpos( $choice, 'bottom' ) || false !== strpos( $choice, 'left' ) || false !== strpos( $choice, 'right' ) );
257
			$script .= 'if(\'' . $choice . '\'===subKey){';
258
			$script .= ( $choice_is_direction ) ? $direction_script . 'else{' : '';
259
			$script .= 'css+=\'' . $args['element'] . '{' . $args['property'] . ':\'+subValue+\';}\';';
260
			$script .= ( $choice_is_direction ) ? '}' : '';
261
			$script .= '}';
262
		} else {
263
			$script .= $direction_script . 'else{';
264
265
			// This is where most object-based fields will go.
266
			$script .= 'css+=\'' . $args['element'] . '{\'+subKey+\':\'+subValue+\'' . $args['units'] . $args['suffix'] . ';}\';';
267
			$script .= '}';
268
		}
269
		$script .= '});';
270
271
		if ( isset( $args['media_query'] ) ) {
272
			$script .= 'css=\'' . $args['media_query'] . '{\'+css+\'}\';';
273
		}
274
275
		return array(
276
			'script' => $property_script . $script,
277
			'css'    => 'css',
278
		);
279
	}
280
281
	/**
282
	 * Processes script generation for typography fields.
283
	 *
284
	 * @access protected
285
	 * @since 3.0.0
286
	 * @param array $args  The arguments for this js_var.
287
	 */
288
	protected function script_var_typography( $args ) {
289
290
		$script = '';
291
		$css    = '';
292
293
		// Load the font using WenFontloader.
294
		// This is a bit ugly because wp_add_inline_script doesn't allow adding <script> directly.
295
		$webfont_loader = 'sc=\'a\';jQuery(\'head\').append(sc.replace(\'a\',\'<\')+\'script>if(!_.isUndefined(WebFont)){WebFont.load({google:{families:["\'+fontFamily.replace( /\"/g, \'&quot;\' )+\':\'+variant+subsetsString+\'"]}});}\'+sc.replace(\'a\',\'<\')+\'/script>\');';
296
297
		// Add the css.
298
		$css_build_array = array(
299
			'font-family'    => 'fontFamily',
300
			'font-size'      => 'fontSize',
301
			'line-height'    => 'lineHeight',
302
			'letter-spacing' => 'letterSpacing',
303
			'word-spacing'   => 'wordSpacing',
304
			'text-align'     => 'textAlign',
305
			'text-transform' => 'textTransform',
306
			'color'          => 'color',
307
			'font-weight'    => 'fontWeight',
308
			'font-style'     => 'fontStyle',
309
		);
310
		$choice_condition = ( isset( $args['choice'] ) && '' !== $args['choice'] && isset( $css_build_array[ $args['choice'] ] ) );
311
		$script .= ( ! $choice_condition ) ? $webfont_loader : '';
312
		foreach ( $css_build_array as $property => $var ) {
313
			if ( $choice_condition && $property !== $args['choice'] ) {
314
				continue;
315
			}
316
			$script .= ( $choice_condition && 'font-family' === $args['choice'] ) ? $webfont_loader : '';
317
318
			if ( 'font-family' === $property || ( isset( $args['choice'] ) && 'font-family' === $args['choice'] ) ) {
319
				$css .= 'fontFamilyCSS=fontFamily;if(0<fontFamily.indexOf(\' \')&&-1===fontFamily.indexOf(\'"\')){fontFamilyCSS=\'"\'+fontFamily+\'"\';}';
320
				$var = 'fontFamilyCSS';
321
			}
322
			$css .= 'css+=(\'\'!==' . $var . ')?\'' . $args['element'] . '\'+\'{' . $property . ':\'+' . $var . '+\';}\':\'\';';
323
		}
324
325
		$script .= $css;
326
		if ( isset( $args['media_query'] ) ) {
327
			$script .= 'css=\'' . $args['media_query'] . '{\'+css+\'}\';';
328
		}
329
		return array(
330
			'script' => $script,
331
			'css'    => 'css',
332
		);
333
	}
334
335
	/**
336
	 * Processes script generation for typography fields.
337
	 *
338
	 * @access protected
339
	 * @since 3.0.0
340
	 * @param array $args  The arguments for this js_var.
341
	 */
342
	protected function script_var_image_array( $args ) {
343
		$return = $this->script_var( $args );
344
		return array(
345
			'script' => 'newval=(!_.isUndefined(newval.url))?newval.url:newval;' . $return['script'],
346
			'css'    => $return['css'],
347
		);
348
	}
349
350
	/**
351
	 * Adds anything we need before the main script.
352
	 *
353
	 * @access private
354
	 * @since 3.0.0
355
	 * @param array $args The field args.
356
	 * @return string;
0 ignored issues
show
Documentation introduced by
The doc-type string; could not be parsed: Expected "|" or "end of type", but got ";" at position 6. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
357
	 */
358
	private function before_script( $args ) {
359
360
		$script = '';
361
362
		if ( isset( $args['type'] ) ) {
363
			switch ( $args['type'] ) {
364
				case 'kirki-typography':
365
					$script .= 'fontFamily=(_.isUndefined(newval[\'font-family\']))?\'\':newval[\'font-family\'];';
366
					$script .= 'variant=(_.isUndefined(newval.variant))?\'400\':newval.variant;';
367
					$script .= 'subsets=(_.isUndefined(newval.subsets))?[]:newval.subsets;';
368
					$script .= 'subsetsString=(_.isObject(newval.subsets))?\':\'+newval.subsets.join(\',\'):\'\';';
369
					$script .= 'fontSize=(_.isUndefined(newval[\'font-size\']))?\'\':newval[\'font-size\'];';
370
					$script .= 'lineHeight=(_.isUndefined(newval[\'line-height\']))?\'\':newval[\'line-height\'];';
371
					$script .= 'letterSpacing=(_.isUndefined(newval[\'letter-spacing\']))?\'\':newval[\'letter-spacing\'];';
372
					$script .= 'wordSpacing=(_.isUndefined(newval[\'word-spacing\']))?\'\':newval[\'word-spacing\'];';
373
					$script .= 'textAlign=(_.isUndefined(newval[\'text-align\']))?\'\':newval[\'text-align\'];';
374
					$script .= 'textTransform=(_.isUndefined(newval[\'text-transform\']))?\'\':newval[\'text-transform\'];';
375
					$script .= 'color=(_.isUndefined(newval.color))?\'\':newval.color;';
376
377
					$script .= 'fw=(!_.isString(newval.variant))?\'400\':newval.variant.match(/\d/g);';
378
					$script .= 'fontWeight=(!_.isObject(fw))?400:fw.join(\'\');';
379
					$script .= 'fontStyle=(-1!==variant.indexOf(\'italic\'))?\'italic\':\'normal\';';
380
					$script .= 'css=\'\';';
381
					break;
382
			}
383
		}
384
		return $script;
385
	}
386
387
	/**
388
	 * Sanitizes the arguments and makes sure they are all there.
389
	 *
390
	 * @access private
391
	 * @since 3.0.0
392
	 * @param array $args The arguments.
393
	 * @return array
394
	 */
395
	private function get_args( $args ) {
396
397
		// Make sure everything is defined to avoid "undefined index" errors.
398
		$args = wp_parse_args( $args, array(
399
			'element'       => '',
400
			'property'      => '',
401
			'prefix'        => '',
402
			'suffix'        => '',
403
			'units'         => '',
404
			'js_callback'   => array( '', '' ),
405
			'value_pattern' => '',
406
		));
407
408
		// Element should be a string.
409
		if ( is_array( $args['element'] ) ) {
410
			$args['element'] = implode( ',', $args['element'] );
411
		}
412
413
		// Make sure arguments that are passed-on to callbacks are strings.
414
		if ( is_array( $args['js_callback'] ) && isset( $args['js_callback'][1] ) && is_array( $args['js_callback'][1] ) ) {
415
			$args['js_callback'][1] = wp_json_encode( $args['js_callback'][1] );
416
		}
417
		return $args;
418
419
	}
420
421
	/**
422
	 * Returns script for value_pattern & replacements.
423
	 *
424
	 * @access private
425
	 * @since 3.0.0
426
	 * @param string $value   The value placeholder.
427
	 * @param array  $js_vars The js_vars argument.
428
	 * @return string         The script.
429
	 */
430
	private function value_pattern_replacements( $value, $js_vars ) {
431
		$script = '';
432
		$alias  = $value;
433
		if ( isset( $js_vars['pattern_replace'] ) ) {
434
			$script .= 'settings=window.wp.customize.get();';
435
			foreach ( $js_vars['pattern_replace'] as $search => $replace ) {
436
				$replace = '\'+settings["' . $replace . '"]+\'';
437
				$value = str_replace( $search, $replace, $js_vars['value_pattern'] );
438
				$value = trim( $value, '+' );
439
			}
440
		}
441
		$value_compiled = str_replace( '$', '\'+' . $alias . '+\'', $value );
442
		$value_compiled = trim( $value_compiled, '+' );
443
		return $script . $alias . '=\'' . $value_compiled . '\';';
444
	}
445
446
	/**
447
	 * Get the callback function/method we're going to use for this field.
448
	 *
449
	 * @access private
450
	 * @since 3.0.0
451
	 * @param array $args The field args.
452
	 * @return string|array A callable function or method.
453
	 */
454
	protected function get_callback( $args ) {
455
456
		switch ( $args['type'] ) {
457
			case 'kirki-background':
458
			case 'kirki-dimensions':
459
			case 'kirki-multicolor':
460
			case 'kirki-sortable':
461
				$callback = array( $this, 'script_var_array' );
462
				break;
463
			case 'kirki-typography':
464
				$callback = array( $this, 'script_var_typography' );
465
				break;
466
			case 'kirki-image-array':
467
				$callback = array( $this, 'script_var_image_array' );
468
				break;
469
			default:
470
				$callback = array( $this, 'script_var' );
471
		}
472
		return $callback;
473
	}
474
}
475