Completed
Push — develop ( e7ec0f...eda9c6 )
by Aristeides
02:52
created

value_pattern_replacements()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 20
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

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