Completed
Pull Request — master (#1454)
by Aristeides
05:35 queued 02:55
created

Kirki_Modules_PostMessage::postmessage()   C

Complexity

Conditions 12
Paths 6

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 16
nc 6
nop 0
dl 0
loc 24
rs 5.2139
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
		$script_id = '';
77
		foreach ( $fields as $field ) {
78
			if ( ! isset( $field['settings'] ) || ! is_string( $field['settings'] ) ) {
79
				continue;
80
			}
81
			$script_id .= $field['settings'];
82
		}
83
		$this->script = get_transient( 'kirki_auto_postmessage' . md5( $script_id ) );
84
		if ( ! $this->script ) {
85
			foreach ( $fields as $field ) {
86
				if ( isset( $field['transport'] ) && 'postMessage' === $field['transport'] && isset( $field['js_vars'] ) && ! empty( $field['js_vars'] ) && is_array( $field['js_vars'] ) && isset( $field['settings'] ) ) {
87
					$this->script .= $this->script( $field );
88
				}
89
			}
90
			$this->script = apply_filters( 'kirki/postmessage/script', $this->script );
91
			set_transient( 'kirki_auto_postmessage' . md5( $script_id ), $this->script, 30 * MINUTE_IN_SECONDS );
92
		}
93
		wp_add_inline_script( 'kirki_auto_postmessage', $this->script, 'after' );
94
95
	}
96
97
	/**
98
	 * Generates script for a single field.
99
	 *
100
	 * @access protected
101
	 * @since 3.0.0
102
	 * @param array $args The arguments.
103
	 */
104
	protected function script( $args ) {
105
106
		$script = 'wp.customize(\'' . $args['settings'] . '\',function(value){value.bind(function(newval){';
107
108
		$add_css = false;
109
		foreach ( $args['js_vars'] as $js_var ) {
110
			if ( ! isset( $js_var['function'] ) || 'html' !== $js_var['function'] ) {
111
				$add_css = true;
112
			}
113
		}
114
115
		if ( $add_css ) {
116
117
			// append unique style tag if not exist
118
			// The style ID.
119
			$style_id = 'kirki-postmessage-' . str_replace( array( '[', ']' ), '', $args['settings'] );
120
			$script .= 'if(null===document.getElementById(\'' . $style_id . '\')||\'undefined\'===typeof document.getElementById(\'' . $style_id . '\')){jQuery(\'head\').append(\'<style id="' . $style_id . '"></style>\');}';
121
		}
122
123
		// Add anything we need before the main script.
124
		$script .= $this->before_script( $args );
125
126
		$field = array(
127
			'scripts' => array(),
128
		);
129
		// Loop through the js_vars and generate the script.
130
		foreach ( $args['js_vars'] as $key => $js_var ) {
131
132
			// Skip styles if "exclude" is defined and value is excluded.
133
			if ( isset( $js_var['exclude'] ) ) {
134
				$js_var['exclude'] = (array) $js_var['exclude'];
135
				$script .= 'exclude=false;';
136
				foreach ( $js_var['exclude'] as $exclussion ) {
137
					$script .= "if(newval=='{$exclussion}'||(''==='{$exclussion}'&&_.isObject(newval)&&_.isEmpty(newval))){exclude=true;}";
138
				}
139
			}
140
			if ( isset( $js_var['element'] ) ) {
141
				// Array to string.
142
				if ( is_array( $js_var['element'] ) ) {
143
					$js_var['element'] = array_unique( $js_var['element'] );
144
					$js_var['element'] = implode( ',', $js_var['element'] );
145
				}
146
				// Replace single quotes with double quotes to avoid issues with the compiled JS.
147
				$js_var['element'] = str_replace( '\'', '"', $js_var['element'] );
148
			}
149
			if ( isset( $js_var['function'] ) && 'html' === $js_var['function'] ) {
150
				$script .= $this->script_html_var( $js_var );
151
				continue;
152
			}
153
			$js_var['index_key'] = $key;
154
			$callback = $this->get_callback( $args );
155
			if ( is_callable( $callback ) ) {
156
				$field['scripts'][ $key ] = call_user_func_array( $callback, array( $js_var, $args ) );
157
				continue;
158
			}
159
			$field['scripts'][ $key ] = $this->script_var( $js_var );
160
		}
161
		$combo_extra_script = '';
162
		$combo_css_script   = '';
163
		foreach ( $field['scripts'] as $script_array ) {
164
			$combo_extra_script .= $script_array['script'];
165
			$combo_css_script   .= ( 'css' !== $combo_css_script ) ? $script_array['css'] : '';
166
		}
167
		$text = ( 'css' === $combo_css_script ) ? 'css' : '\'' . $combo_css_script . '\'';
168
169
		$script .= $combo_extra_script;
170
		$script .= "var cssContent={$text};";
171
		if ( isset( $js_var['exclude'] ) ) {
172
			$script .= 'if(true===exclude){cssContent="";}';
173
		}
174
		if ( $add_css ) {
175
			$script .= "jQuery('#{$style_id}').text(cssContent);";
176
			$script .= "jQuery('#{$style_id}').appendTo('head');";
177
		}
178
		$script .= '});});';
179
		return $script;
180
	}
181
182
	/**
183
	 * Generates script for a single js_var when using "html" as function.
184
	 *
185
	 * @access protected
186
	 * @since 3.0.0
187
	 * @param array $args  The arguments for this js_var.
188
	 */
189
	protected function script_html_var( $args ) {
190
191
		$script  = ( isset( $args['choice'] ) ) ? "newval=newval['{$args['choice']}'];" : '';
192
193
		// Apply the value_pattern.
194
		if ( isset( $args['value_pattern'] ) && '' !== $args['value_pattern'] ) {
195
			$script .= $this->value_pattern_replacements( 'newval', $args );
196
		}
197
198
		if ( isset( $args['attr'] ) ) {
199
			$script .= "jQuery('{$args['element']}').attr('{$args['attr']}',newval);";
200
			return $script;
201
		}
202
		$script .= "jQuery('{$args['element']}').html(newval);";
203
		return $script;
204
	}
205
206
	/**
207
	 * Generates script for a single js_var.
208
	 *
209
	 * @access protected
210
	 * @since 3.0.0
211
	 * @param array $args  The arguments for this js_var.
212
	 */
213
	protected function script_var( $args ) {
214
		$script = '';
215
		$property_script = '';
216
217
		$value_key = 'newval' . $args['index_key'];
218
		$property_script .= $value_key . '=newval;';
219
220
		$args = $this->get_args( $args );
221
222
		// Apply callback to the value if a callback is defined.
223
		if ( ! empty( $args['js_callback'] ) && is_array( $args['js_callback'] ) && isset( $args['js_callback'][0] ) && ! empty( $args['js_callback'][0] ) ) {
224
			$args['js_callback'][1] = isset( $args['js_callback'][1] ) ? $args['js_callback'][1] : '';
225
			$script .= $value_key . '=' . $args['js_callback'][0] . '(' . $value_key . ',' . $args['js_callback'][1] . ');';
226
		}
227
228
		// Apply the value_pattern.
229
		if ( '' !== $args['value_pattern'] ) {
230
			$script .= $this->value_pattern_replacements( $value_key, $args );
231
		}
232
233
		// Tweak to add url() for background-images.
234
		if ( 'background-image' === $args['property'] && ( ! isset( $args['value_pattern'] ) || false === strpos( $args['value_pattern'], 'gradient' ) ) ) {
235
			$script .= 'if(-1===' . $value_key . '.indexOf(\'url(\')){' . $value_key . '=\'url("\'+' . $value_key . '+\'")\';}';
236
		}
237
238
		// Apply prefix.
239
		$value = $value_key;
240
		if ( '' !== $args['prefix'] ) {
241
			$value = "'" . $args['prefix'] . "'+" . $value_key;
242
		}
243
		$css = $args['element'] . '{' . $args['property'] . ':\'+' . $value . '+\'' . $args['units'] . $args['suffix'] . ';}';
244
		if ( isset( $args['media_query'] ) ) {
245
			$css = $args['media_query'] . '{' . $css . '}';
246
		}
247
		return array(
248
			'script' => $property_script . $script,
249
			'css'    => $css,
250
		);
251
	}
252
253
	/**
254
	 * Processes script generation for fields that save an array.
255
	 *
256
	 * @access protected
257
	 * @since 3.0.0
258
	 * @param array $args  The arguments for this js_var.
259
	 */
260
	protected function script_var_array( $args ) {
261
262
		$script = ( 0 === $args['index_key'] ) ? 'css=\'\';' : '';
263
		$property_script = '';
264
265
		// Define choice.
266
		$choice  = ( isset( $args['choice'] ) && '' !== $args['choice'] ) ? $args['choice'] : '';
267
268
		$value_key = 'newval' . $args['index_key'];
269
		$property_script .= $value_key . '=newval;';
270
271
		$args = $this->get_args( $args );
272
273
		// Apply callback to the value if a callback is defined.
274
		if ( ! empty( $args['js_callback'] ) && is_array( $args['js_callback'] ) && isset( $args['js_callback'][0] ) && ! empty( $args['js_callback'][0] ) ) {
275
			$script .= $value_key . '=' . $args['js_callback'][0] . '(' . $value_key . ',' . $args['js_callback'][1] . ');';
276
		}
277
		$script .= '_.each(' . $value_key . ', function(subValue,subKey){';
278
279
		// Apply the value_pattern.
280
		if ( '' !== $args['value_pattern'] ) {
281
			$script .= $this->value_pattern_replacements( 'subValue', $args );
282
		}
283
284
		// Tweak to add url() for background-images.
285
		if ( '' === $choice || 'background-image' === $choice ) {
286
			$script .= 'if(\'background-image\'===\'' . $args['property'] . '\'||\'background-image\'===subKey){';
287
			$script .= 'if(-1===subValue.indexOf(\'url(\')){subValue=\'url("\'+subValue+\'")\';}';
288
			$script .= '}';
289
		}
290
291
		// Apply prefix.
292
		$value = $value_key;
293
		if ( '' !== $args['prefix'] ) {
294
			$value = '\'' . $args['prefix'] . '\'+subValue';
295
		}
296
297
		// Allows us to apply this just for a specific choice in the array of the values.
298
		if ( '' !== $choice ) {
299
			$script .= 'if(\'' . $choice . '\'===subKey){';
300
			$script .= 'css+=\'' . $args['element'] . '{' . $args['property'] . ':\'+subValue+\';}\';';
301
			$script .= '}';
302
		} else {
303
			// Mostly used for padding, margin & position properties.
304
			$script .= 'if(_.contains([\'top\',\'bottom\',\'left\',\'right\'],subKey)){';
305
			$script .= 'css+=\'' . $args['element'] . '{' . $args['property'] . '-\'+subKey+\':\'+subValue+\'' . $args['units'] . $args['suffix'] . ';}\';}';
306
			$script .= 'else{';
307
308
			// This is where most object-based fields will go.
309
			$script .= 'css+=\'' . $args['element'] . '{\'+subKey+\':\'+subValue+\'' . $args['units'] . $args['suffix'] . ';}\';';
310
			$script .= '}';
311
		}
312
		$script .= '});';
313
314
		if ( isset( $args['media_query'] ) ) {
315
			$script .= 'css=\'' . $args['media_query'] . '{\'+css+\'}\';';
316
		}
317
318
		return array(
319
			'script' => $property_script . $script,
320
			'css'    => 'css',
321
		);
322
	}
323
324
	/**
325
	 * Processes script generation for typography fields.
326
	 *
327
	 * @access protected
328
	 * @since 3.0.0
329
	 * @param array $args  The arguments for this js_var.
330
	 * @param array $field The field arguments.
331
	 */
332
	protected function script_var_typography( $args, $field ) {
333
334
		$script = '';
335
		$css    = '';
336
337
		// Load the font using WenFontloader.
338
		// This is a bit ugly because wp_add_inline_script doesn't allow adding <script> directly.
339
		$webfont_loader = 'sc=\'a\';jQuery(\'head\').append(sc.replace(\'a\',\'<\')+\'script>if(!_.isUndefined(WebFont)&&fontFamily){WebFont.load({google:{families:["\'+fontFamily.replace( /\"/g, \'&quot;\' )+\':\'+variant+subsetsString+\'"]}});}\'+sc.replace(\'a\',\'<\')+\'/script>\');';
340
341
		// Add the css.
342
		$css_build_array = array(
343
			'font-family'    => 'fontFamily',
344
			'font-size'      => 'fontSize',
345
			'line-height'    => 'lineHeight',
346
			'letter-spacing' => 'letterSpacing',
347
			'word-spacing'   => 'wordSpacing',
348
			'text-align'     => 'textAlign',
349
			'text-transform' => 'textTransform',
350
			'color'          => 'color',
351
			'font-weight'    => 'fontWeight',
352
			'font-style'     => 'fontStyle',
353
		);
354
		$choice_condition = ( isset( $args['choice'] ) && '' !== $args['choice'] && isset( $css_build_array[ $args['choice'] ] ) );
355
		$script .= ( ! $choice_condition ) ? $webfont_loader : '';
356
		foreach ( $css_build_array as $property => $var ) {
357
			if ( $choice_condition && $property !== $args['choice'] ) {
358
				continue;
359
			}
360
			// Fixes https://github.com/aristath/kirki/issues/1436.
361
			if ( ! isset( $field['default'] ) || (
362
				( 'font-family' === $property && ! isset( $field['default']['font-family'] ) ) ||
363
				( 'font-size' === $property && ! isset( $field['default']['font-size'] ) ) ||
364
				( 'line-height' === $property && ! isset( $field['default']['line-height'] ) ) ||
365
				( 'letter-spacing' === $property && ! isset( $field['default']['letter-spacing'] ) ) ||
366
				( 'word-spacing' === $property && ! isset( $field['default']['word-spacing'] ) ) ||
367
				( 'text-align' === $property && ! isset( $field['default']['text-align'] ) ) ||
368
				( 'text-transform' === $property && ! isset( $field['default']['text-transform'] ) ) ||
369
				( 'color' === $property && ! isset( $field['default']['color'] ) ) ||
370
				( 'font-weight' === $property && ! isset( $field['default']['variant'] ) && ! isset( $field['default']['font-weight'] ) ) ||
371
				( 'font-style' === $property && ! isset( $field['default']['variant'] ) && ! isset( $field['default']['font-style'] ) )
372
				) ) {
373
				continue;
374
			}
375
			$script .= ( $choice_condition && 'font-family' === $args['choice'] ) ? $webfont_loader : '';
376
377
			if ( 'font-family' === $property || ( isset( $args['choice'] ) && 'font-family' === $args['choice'] ) ) {
378
				$css .= 'fontFamilyCSS=fontFamily;if(0<fontFamily.indexOf(\' \')&&-1===fontFamily.indexOf(\'"\')){fontFamilyCSS=\'"\'+fontFamily+\'"\';}';
379
				$var = 'fontFamilyCSS';
380
			}
381
			$css .= 'css+=(\'\'!==' . $var . ')?\'' . $args['element'] . '\'+\'{' . $property . ':\'+' . $var . '+\';}\':\'\';';
382
		}
383
384
		$script .= $css;
385
		if ( isset( $args['media_query'] ) ) {
386
			$script .= 'css=\'' . $args['media_query'] . '{\'+css+\'}\';';
387
		}
388
		return array(
389
			'script' => $script,
390
			'css'    => 'css',
391
		);
392
	}
393
394
	/**
395
	 * Processes script generation for typography fields.
396
	 *
397
	 * @access protected
398
	 * @since 3.0.0
399
	 * @param array $args  The arguments for this js_var.
400
	 */
401
	protected function script_var_image( $args ) {
402
		$return = $this->script_var( $args );
403
		return array(
404
			'script' => 'newval=(!_.isUndefined(newval.url))?newval.url:newval;' . $return['script'],
405
			'css'    => $return['css'],
406
		);
407
	}
408
409
	/**
410
	 * Adds anything we need before the main script.
411
	 *
412
	 * @access private
413
	 * @since 3.0.0
414
	 * @param array $args The field args.
415
	 * @return string
416
	 */
417
	private function before_script( $args ) {
418
419
		$script = '';
420
421
		if ( isset( $args['type'] ) ) {
422
			switch ( $args['type'] ) {
423
				case 'kirki-typography':
424
					$script .= 'fontFamily=(_.isUndefined(newval[\'font-family\']))?\'\':newval[\'font-family\'];';
425
					$script .= 'variant=(_.isUndefined(newval.variant))?\'400\':newval.variant;';
426
					$script .= 'subsets=(_.isUndefined(newval.subsets))?[]:newval.subsets;';
427
					$script .= 'subsetsString=(_.isObject(newval.subsets))?\':\'+newval.subsets.join(\',\'):\'\';';
428
					$script .= 'fontSize=(_.isUndefined(newval[\'font-size\']))?\'\':newval[\'font-size\'];';
429
					$script .= 'lineHeight=(_.isUndefined(newval[\'line-height\']))?\'\':newval[\'line-height\'];';
430
					$script .= 'letterSpacing=(_.isUndefined(newval[\'letter-spacing\']))?\'\':newval[\'letter-spacing\'];';
431
					$script .= 'wordSpacing=(_.isUndefined(newval[\'word-spacing\']))?\'\':newval[\'word-spacing\'];';
432
					$script .= 'textAlign=(_.isUndefined(newval[\'text-align\']))?\'\':newval[\'text-align\'];';
433
					$script .= 'textTransform=(_.isUndefined(newval[\'text-transform\']))?\'\':newval[\'text-transform\'];';
434
					$script .= 'color=(_.isUndefined(newval.color))?\'\':newval.color;';
435
436
					$script .= 'fw=(!_.isString(newval.variant))?\'400\':newval.variant.match(/\d/g);';
437
					$script .= 'fontWeight=(!_.isObject(fw))?400:fw.join(\'\');';
438
					$script .= 'fontStyle=(-1!==variant.indexOf(\'italic\'))?\'italic\':\'normal\';';
439
					$script .= 'css=\'\';';
440
					break;
441
			}
442
		}
443
		return $script;
444
	}
445
446
	/**
447
	 * Sanitizes the arguments and makes sure they are all there.
448
	 *
449
	 * @access private
450
	 * @since 3.0.0
451
	 * @param array $args The arguments.
452
	 * @return array
453
	 */
454
	private function get_args( $args ) {
455
456
		// Make sure everything is defined to avoid "undefined index" errors.
457
		$args = wp_parse_args( $args, array(
458
			'element'       => '',
459
			'property'      => '',
460
			'prefix'        => '',
461
			'suffix'        => '',
462
			'units'         => '',
463
			'js_callback'   => array( '', '' ),
464
			'value_pattern' => '',
465
		));
466
467
		// Element should be a string.
468
		if ( is_array( $args['element'] ) ) {
469
			$args['element'] = implode( ',', $args['element'] );
470
		}
471
472
		// Make sure arguments that are passed-on to callbacks are strings.
473
		if ( is_array( $args['js_callback'] ) && isset( $args['js_callback'][1] ) && is_array( $args['js_callback'][1] ) ) {
474
			$args['js_callback'][1] = wp_json_encode( $args['js_callback'][1] );
475
		}
476
		return $args;
477
478
	}
479
480
	/**
481
	 * Returns script for value_pattern & replacements.
482
	 *
483
	 * @access private
484
	 * @since 3.0.0
485
	 * @param string $value   The value placeholder.
486
	 * @param array  $js_vars The js_vars argument.
487
	 * @return string         The script.
488
	 */
489
	private function value_pattern_replacements( $value, $js_vars ) {
490
		$script = '';
491
		$alias  = $value;
492
		if ( ! isset( $js_vars['value_pattern'] ) ) {
493
			return $value;
494
		}
495
		$value = $js_vars['value_pattern'];
496
		if ( isset( $js_vars['pattern_replace'] ) ) {
497
			$script .= 'settings=window.wp.customize.get();';
498
			foreach ( $js_vars['pattern_replace'] as $search => $replace ) {
499
				$replace = '\'+settings["' . $replace . '"]+\'';
500
				$value = str_replace( $search, $replace, $js_vars['value_pattern'] );
501
				$value = trim( $value, '+' );
502
			}
503
		}
504
		$value_compiled = str_replace( '$', '\'+' . $alias . '+\'', $value );
505
		$value_compiled = trim( $value_compiled, '+' );
506
507
		return $script . $alias . '=\'' . $value_compiled . '\';';
508
	}
509
510
	/**
511
	 * Get the callback function/method we're going to use for this field.
512
	 *
513
	 * @access private
514
	 * @since 3.0.0
515
	 * @param array $args The field args.
516
	 * @return string|array A callable function or method.
517
	 */
518
	protected function get_callback( $args ) {
519
520
		switch ( $args['type'] ) {
521
			case 'kirki-background':
522
			case 'kirki-dimensions':
523
			case 'kirki-multicolor':
524
			case 'kirki-sortable':
525
				$callback = array( $this, 'script_var_array' );
526
				break;
527
			case 'kirki-typography':
528
				$callback = array( $this, 'script_var_typography' );
529
				break;
530
			case 'kirki-image':
531
				$callback = array( $this, 'script_var_image' );
532
				break;
533
			default:
534
				$callback = array( $this, 'script_var' );
535
		}
536
		return $callback;
537
	}
538
}
539