Completed
Push — develop ( 656b88...85b7b9 )
by Aristeides
06:46
created

Kirki_Control_Repeater::row_label()   C

Complexity

Conditions 12
Paths 9

Size

Total Lines 24
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 10
nc 9
nop 1
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
 * Customizer Control: repeater.
4
 *
5
 * @package     Kirki
6
 * @subpackage  Controls
7
 * @copyright   Copyright (c) 2017, Aristeides Stathopoulos
8
 * @license     http://opensource.org/licenses/https://opensource.org/licenses/MIT
9
 * @since       2.0
10
 */
11
12
// Exit if accessed directly.
13
if ( ! defined( 'ABSPATH' ) ) {
14
	exit;
15
}
16
17
/**
18
 * Repeater control
19
 */
20
class Kirki_Control_Repeater extends WP_Customize_Control {
21
22
	/**
23
	 * The control type.
24
	 *
25
	 * @access public
26
	 * @var string
27
	 */
28
	public $type = 'repeater';
29
30
	/**
31
	 * Used to automatically generate all CSS output.
32
	 *
33
	 * @access public
34
	 * @var array
35
	 */
36
	public $output = array();
37
38
	/**
39
	 * Data type
40
	 *
41
	 * @access public
42
	 * @var string
43
	 */
44
	public $option_type = 'theme_mod';
45
46
	/**
47
	 * The kirki_config we're using for this control
48
	 *
49
	 * @access public
50
	 * @var string
51
	 */
52
	public $kirki_config = 'global';
53
54
	/**
55
	 * The fields that each container row will contain.
56
	 *
57
	 * @access public
58
	 * @var array
59
	 */
60
	public $fields = array();
61
62
	/**
63
	 * Will store a filtered version of value for advenced fields (like images).
64
	 *
65
	 * @access protected
66
	 * @var array
67
	 */
68
	protected $filtered_value = array();
69
70
	/**
71
	 * The row label
72
	 *
73
	 * @access public
74
	 * @var array
75
	 */
76
	public $row_label = array();
77
78
	/**
79
	 * Constructor.
80
	 * Supplied `$args` override class property defaults.
81
	 * If `$args['settings']` is not defined, use the $id as the setting ID.
82
	 *
83
	 * @param WP_Customize_Manager $manager Customizer bootstrap instance.
84
	 * @param string               $id      Control ID.
85
	 * @param array                $args    {@see WP_Customize_Control::__construct}.
86
	 */
87
	public function __construct( $manager, $id, $args = array() ) {
88
89
		parent::__construct( $manager, $id, $args );
90
91
		// Set up defaults for row labels.
92
		$this->row_label = array(
93
			'type' => 'text',
94
			'value' => esc_attr__( 'row', 'kirki' ),
95
			'field' => false,
96
		);
97
98
		// Validate row-labels.
99
		$this->row_label( $args );
100
101
		if ( empty( $this->button_label ) ) {
102
			/* translators: %s represents the label of the row. */
103
			$this->button_label = sprintf( esc_attr__( 'Add new %s', 'kirki' ), $this->row_label['value'] );
104
		}
105
106
		if ( empty( $args['fields'] ) || ! is_array( $args['fields'] ) ) {
107
			$args['fields'] = array();
108
		}
109
110
		// An array to store keys of fields that need to be filtered.
111
		$media_fields_to_filter = array();
112
113
		foreach ( $args['fields'] as $key => $value ) {
114
			if ( ! isset( $value['default'] ) ) {
115
				$args['fields'][ $key ]['default'] = '';
116
			}
117
			if ( ! isset( $value['label'] ) ) {
118
				$args['fields'][ $key ]['label'] = '';
119
			}
120
			$args['fields'][ $key ]['id']      = $key;
121
122
			// We check if the filed is an uploaded media ( image , file, video, etc.. ).
123
			if ( isset( $value['type'] ) ) {
124
				switch ( $value['type'] ) {
125
					case 'image':
126
					case 'cropped_image':
127
					case 'upload':
128
						// We add it to the list of fields that need some extra filtering/processing.
129
						$media_fields_to_filter[ $key ] = true;
130
						break;
131
132
					case 'dropdown-pages':
133
						// If the field is a dropdown-pages field then add it to args.
134
						$dropdown = wp_dropdown_pages(
135
							array(
136
								'name'              => '',
137
								'echo'              => 0,
138
								'show_option_none'  => esc_attr__( 'Select a Page', 'kirki' ),
139
								'option_none_value' => '0',
140
								'selected'          => '',
141
							)
142
						);
143
						// Hackily add in the data link parameter.
144
						$dropdown = str_replace( '<select', '<select data-field="' . esc_attr( $args['fields'][ $key ]['id'] ) . '"' . $this->get_link(), $dropdown );
145
						$args['fields'][ $key ]['dropdown'] = $dropdown;
146
						break;
147
				}
148
			}
149
		} // End foreach().
150
151
		$this->fields = $args['fields'];
152
153
		// Now we are going to filter the fields.
154
		// First we create a copy of the value that would be used otherwise.
155
		$this->filtered_value = $this->value();
156
157
		if ( is_array( $this->filtered_value ) && ! empty( $this->filtered_value ) ) {
158
159
			// We iterate over the list of fields.
160
			foreach ( $this->filtered_value as &$filtered_value_field ) {
161
162
				if ( is_array( $filtered_value_field ) && ! empty( $filtered_value_field ) ) {
163
164
					// We iterate over the list of properties for this field.
165
					foreach ( $filtered_value_field as $key => &$value ) {
166
167
						// We check if this field was marked as requiring extra filtering (in this case image, cropped_images, upload).
168
						if ( array_key_exists( $key, $media_fields_to_filter ) ) {
169
170
							// What follows was made this way to preserve backward compatibility.
171
							// The repeater control use to store the URL for images instead of the attachment ID.
172
							// We check if the value look like an ID (otherwise it's probably a URL so don't filter it).
173
							if ( is_numeric( $value ) ) {
174
175
								// "sanitize" the value.
176
								$attachment_id = (int) $value;
177
178
								// Try to get the attachment_url.
179
								$url = wp_get_attachment_url( $attachment_id );
180
181
								$filename = basename( get_attached_file( $attachment_id ) );
182
183
								// If we got a URL.
184
								if ( $url ) {
185
186
									// 'id' is needed for form hidden value, URL is needed to display the image.
187
									$value = array(
188
										'id'  => $attachment_id,
189
										'url' => $url,
190
										'filename' => $filename,
191
									);
192
								}
193
							}
194
						}
195
					}
196
				}
197
			} // End foreach().
198
		} // End if().
199
	}
200
201
	/**
202
	 * Refresh the parameters passed to the JavaScript via JSON.
203
	 *
204
	 * @access public
205
	 */
206
	public function to_json() {
207
		parent::to_json();
208
209
		$this->json['default'] = ( isset( $this->default ) ) ? $this->default : $this->setting->default;
210
		$this->json['output']  = $this->output;
211
		$this->json['value']   = $this->value();
212
		$this->json['choices'] = $this->choices;
213
		$this->json['link']    = $this->get_link();
214
		$this->json['id']      = $this->id;
215
216
		$this->json['inputAttrs'] = '';
217
		foreach ( $this->input_attrs as $attr => $value ) {
218
			$this->json['inputAttrs'] .= $attr . '="' . esc_attr( $value ) . '" ';
219
		}
220
221
		$fields = $this->fields;
222
223
		$this->json['fields'] = $fields;
224
		$this->json['row_label'] = $this->row_label;
225
226
		// If filtered_value has been set and is not empty we use it instead of the actual value.
227
		if ( is_array( $this->filtered_value ) && ! empty( $this->filtered_value ) ) {
228
			$this->json['value'] = $this->filtered_value;
229
		}
230
		$this->json['value'] = apply_filters( "kirki/controls/repeater/value/{$this->id}", $this->json['value'] );
231
	}
232
233
	/**
234
	 * Enqueue control related scripts/styles.
235
	 *
236
	 * @access public
237
	 */
238
	public function enqueue() {
239
240
		// If we have a color picker field we need to enqueue the WordPress Color Picker style and script.
241
		if ( is_array( $this->fields ) && ! empty( $this->fields ) ) {
242
			foreach ( $this->fields as $field ) {
243
				if ( isset( $field['type'] ) ) {
244
245
					// Some field-types require extra scripts.
246
					switch ( $field['type'] ) {
247
						case 'color':
248
							wp_enqueue_script( 'wp-color-picker' );
249
							wp_enqueue_style( 'wp-color-picker' );
250
							break;
251
						case 'select':
252
						case 'dropdown-pages':
253
							wp_enqueue_script( 'select2', trailingslashit( Kirki::$url ) . 'assets/vendor/select2/js/select2.full.js', array( 'jquery' ), '4.0.3', true );
254
							wp_enqueue_style( 'select2', trailingslashit( Kirki::$url ) . 'assets/vendor/select2/css/select2.css', array(), '4.0.3' );
255
							wp_enqueue_style( 'kirki-select2', trailingslashit( Kirki::$url ) . 'assets/vendor/select2/kirki.css', null );
256
							break;
257
					}
258
				}
259
			}
260
		}
261
262
		wp_enqueue_script( 'kirki-repeater', trailingslashit( Kirki::$url ) . 'controls/repeater/repeater.js', array( 'jquery', 'customize-base', 'jquery-ui-core', 'jquery-ui-sortable' ), false, true );
263
		wp_enqueue_style( 'kirki-repeater-css', trailingslashit( Kirki::$url ) . 'controls/repeater/repeater.css', null );
264
	}
265
266
	/**
267
	 * Render the control's content.
268
	 * Allows the content to be overriden without having to rewrite the wrapper in $this->render().
269
	 *
270
	 * @access protected
271
	 */
272
	protected function render_content() {
273
		?>
274
		<label>
275
			<?php if ( ! empty( $this->label ) ) : ?>
276
				<span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span>
277
			<?php endif; ?>
278
			<?php if ( ! empty( $this->description ) ) : ?>
279
				<span class="description customize-control-description"><?php echo wp_kses_post( $this->description ); ?></span>
280
			<?php endif; ?>
281
			<input type="hidden" {{{ data.inputAttrs }}} value="" <?php echo wp_kses_post( $this->get_link() ); ?> />
282
		</label>
283
284
		<ul class="repeater-fields"></ul>
285
286
		<?php if ( isset( $this->choices['limit'] ) ) : ?>
287
			<?php // @codingStandardsIgnoreLine ?>
288
			<?php /* translators: %s represents the number of rows we're limiting the repeater to allow. */ ?>
289
			<p class="limit"><?php printf( esc_attr__( 'Limit: %s rows', 'kirki' ), esc_html( $this->choices['limit'] ) ); ?></p>
290
		<?php endif; ?>
291
		<button class="button-secondary repeater-add"><?php echo esc_html( $this->button_label ); ?></button>
292
293
		<?php
294
295
		$this->repeater_js_template();
296
297
	}
298
299
	/**
300
	 * An Underscore (JS) template for this control's content (but not its container).
301
	 * Class variables for this control class are available in the `data` JS object.
302
	 *
303
	 * @access public
304
	 */
305
	public function repeater_js_template() {
306
		?>
307
		<script type="text/html" class="customize-control-repeater-content">
308
			<# var field; var index = data.index; #>
309
310
			<li class="repeater-row minimized" data-row="{{{ index }}}">
311
312
				<div class="repeater-row-header">
313
					<span class="repeater-row-label"></span>
314
					<i class="dashicons dashicons-arrow-down repeater-minimize"></i>
315
				</div>
316
				<div class="repeater-row-content">
317
					<# _.each( data, function( field, i ) { #>
318
319
						<div class="repeater-field repeater-field-{{{ field.type }}}">
320
321
							<# if ( 'text' === field.type || 'url' === field.type || 'link' === field.type || 'email' === field.type || 'tel' === field.type || 'date' === field.type || 'number' === field.type ) { #>
322
								<# var fieldExtras = ''; #>
323
								<# if ( 'link' === field.type ) { #>
324
									<# field.type = 'url' #>
325
								<# } #>
326
327
								<# if ( 'number' === field.type ) { #>
328
									<# if ( ! _.isUndefined( field.choices ) && ! _.isUndefined( field.choices.min ) ) { #>
329
										<# fieldExtras += ' min="' + field.choices.min + '"'; #>
330
									<# } #>
331
									<# if ( ! _.isUndefined( field.choices ) && ! _.isUndefined( field.choices.max ) ) { #>
332
										<# fieldExtras += ' max="' + field.choices.max + '"'; #>
333
									<# } #>
334
									<# if ( ! _.isUndefined( field.choices ) && ! _.isUndefined( field.choices.step ) ) { #>
335
										<# fieldExtras += ' step="' + field.choices.step + '"'; #>
336
									<# } #>
337
								<# } #>
338
339
								<label>
340
									<# if ( field.label ) { #><span class="customize-control-title">{{ field.label }}</span><# } #>
341
									<# if ( field.description ) { #><span class="description customize-control-description">{{ field.description }}</span><# } #>
342
									<input type="{{field.type}}" name="" value="{{{ field.default }}}" data-field="{{{ field.id }}}"{{ fieldExtras }}>
343
								</label>
344
345
							<# } else if ( 'number' === field.type ) { #>
346
347
								<label>
348
									<# if ( field.label ) { #><span class="customize-control-title">{{ field.label }}</span><# } #>
349
									<# if ( field.description ) { #><span class="description customize-control-description">{{ field.description }}</span><# } #>
350
									<input type="{{ field.type }}" name="" value="{{{ field.default }}}" data-field="{{{ field.id }}}"{{ numberFieldExtras }}>
351
								</label>
352
353
							<# } else if ( 'hidden' === field.type ) { #>
354
355
								<input type="hidden" data-field="{{{ field.id }}}" <# if ( field.default ) { #> value="{{{ field.default }}}" <# } #> />
356
357
							<# } else if ( 'checkbox' === field.type ) { #>
358
359
								<label>
360
									<input type="checkbox" value="true" data-field="{{{ field.id }}}" <# if ( field.default ) { #> checked="checked" <# } #> /> {{ field.label }}
361
									<# if ( field.description ) { #>{{ field.description }}<# } #>
362
								</label>
363
364
							<# } else if ( 'select' === field.type ) { #>
365
366
								<label>
367
									<# if ( field.label ) { #><span class="customize-control-title">{{ field.label }}</span><# } #>
368
									<# if ( field.description ) { #><span class="description customize-control-description">{{ field.description }}</span><# } #>
369
									<select data-field="{{{ field.id }}}"<# if ( ! _.isUndefined( field.multiple ) && false !== field.multiple ) { #> multiple="multiple" data-multiple="{{ field.multiple }}"<# } #>>
370
										<# _.each( field.choices, function( choice, i ) { #>
371
											<option value="{{{ i }}}" <# if ( field.default == i ) { #> selected="selected" <# } #>>{{ choice }}</option>
372
										<# }); #>
373
									</select>
374
								</label>
375
376
							<# } else if ( 'dropdown-pages' === field.type ) { #>
377
378
								<label>
379
									<# if ( field.label ) { #><span class="customize-control-title">{{{ data.label }}}</span><# } #>
380
									<# if ( field.description ) { #><span class="description customize-control-description">{{{ field.description }}}</span><# } #>
381
									<div class="customize-control-content repeater-dropdown-pages">{{{ field.dropdown }}}</div>
382
								</label>
383
384
							<# } else if ( 'radio' === field.type ) { #>
385
386
								<label>
387
									<# if ( field.label ) { #><span class="customize-control-title">{{ field.label }}</span><# } #>
388
									<# if ( field.description ) { #><span class="description customize-control-description">{{ field.description }}</span><# } #>
389
390
									<# _.each( field.choices, function( choice, i ) { #>
391
										<label><input type="radio" name="{{{ field.id }}}{{ index }}" data-field="{{{ field.id }}}" value="{{{ i }}}" <# if ( field.default == i ) { #> checked="checked" <# } #>> {{ choice }} <br/></label>
392
									<# }); #>
393
								</label>
394
395
							<# } else if ( 'radio-image' === field.type ) { #>
396
397
								<label>
398
									<# if ( field.label ) { #><span class="customize-control-title">{{ field.label }}</span><# } #>
399
									<# if ( field.description ) { #><span class="description customize-control-description">{{ field.description }}</span><# } #>
400
401
									<# _.each( field.choices, function( choice, i ) { #>
402
										<input type="radio" id="{{{ field.id }}}_{{ index }}_{{{ i }}}" name="{{{ field.id }}}{{ index }}" data-field="{{{ field.id }}}" value="{{{ i }}}" <# if ( field.default == i ) { #> checked="checked" <# } #>>
403
											<label for="{{{ field.id }}}_{{ index }}_{{{ i }}}"><img src="{{ choice }}"></label>
404
										</input>
405
									<# }); #>
406
								</label>
407
408
							<# } else if ( 'color' === field.type ) { #>
409
410
								<# var defaultValue = '';
411
								if ( field.default ) {
412
									defaultValue = ( '#' !== field.default.substring( 0, 1 ) ) ? '#' + field.default : field.default;
413
									defaultValue = ' data-default-color=' + defaultValue; // Quotes added automatically.
414
								} #>
415
								<label>
416
									<# if ( field.label ) { #><span class="customize-control-title">{{{ field.label }}}</span><# } #>
417
									<# if ( field.description ) { #><span class="description customize-control-description">{{{ field.description }}}</span><# } #>
418
									<input class="color-picker-hex" type="text" maxlength="7" placeholder="<?php esc_attr_e( 'Hex Value', 'kirki' ); ?>"  value="{{{ field.default }}}" data-field="{{{ field.id }}}" {{ defaultValue }} />
419
420
								</label>
421
422
							<# } else if ( 'textarea' === field.type ) { #>
423
424
								<# if ( field.label ) { #><span class="customize-control-title">{{ field.label }}</span><# } #>
425
								<# if ( field.description ) { #><span class="description customize-control-description">{{ field.description }}</span><# } #>
426
								<textarea rows="5" data-field="{{{ field.id }}}">{{ field.default }}</textarea>
427
428
							<# } else if ( field.type === 'image' || field.type === 'cropped_image' ) { #>
429
430
								<label>
431
									<# if ( field.label ) { #><span class="customize-control-title">{{ field.label }}</span><# } #>
432
									<# if ( field.description ) { #><span class="description customize-control-description">{{ field.description }}</span><# } #>
433
								</label>
434
435
								<figure class="kirki-image-attachment" data-placeholder="<?php esc_attr_e( 'No Image Selected', 'kirki' ); ?>" >
436
									<# if ( field.default ) { #>
437
										<# var defaultImageURL = ( field.default.url ) ? field.default.url : field.default; #>
438
										<img src="{{{ defaultImageURL }}}">
439
									<# } else { #>
440
										<?php esc_attr_e( 'No Image Selected', 'kirki' ); ?>
441
									<# } #>
442
								</figure>
443
444
								<div class="actions">
445
									<button type="button" class="button remove-button<# if ( ! field.default ) { #> hidden<# } #>"><?php esc_attr_e( 'Remove', 'kirki' ); ?></button>
446
									<button type="button" class="button upload-button" data-label=" <?php esc_attr_e( 'Add Image', 'kirki' ); ?>" data-alt-label="<?php echo esc_attr_e( 'Change Image', 'kirki' ); ?>" >
447
										<# if ( field.default ) { #>
448
											<?php esc_attr_e( 'Change Image', 'kirki' ); ?>
449
										<# } else { #>
450
											<?php esc_attr_e( 'Add Image', 'kirki' ); ?>
451
										<# } #>
452
									</button>
453
									<# if ( field.default.id ) { #>
454
										<input type="hidden" class="hidden-field" value="{{{ field.default.id }}}" data-field="{{{ field.id }}}" >
455
									<# } else { #>
456
										<input type="hidden" class="hidden-field" value="{{{ field.default }}}" data-field="{{{ field.id }}}" >
457
									<# } #>
458
								</div>
459
460
							<# } else if ( field.type === 'upload' ) { #>
461
462
								<label>
463
									<# if ( field.label ) { #><span class="customize-control-title">{{ field.label }}</span><# } #>
464
									<# if ( field.description ) { #><span class="description customize-control-description">{{ field.description }}</span><# } #>
465
								</label>
466
467
								<figure class="kirki-file-attachment" data-placeholder="<?php esc_attr_e( 'No File Selected', 'kirki' ); ?>" >
468
									<# if ( field.default ) { #>
469
										<# var defaultFilename = ( field.default.filename ) ? field.default.filename : field.default; #>
470
										<span class="file"><span class="dashicons dashicons-media-default"></span> {{ defaultFilename }}</span>
471
									<# } else { #>
472
										<?php esc_attr_e( 'No File Selected', 'kirki' ); ?>
473
									<# } #>
474
								</figure>
475
476
								<div class="actions">
477
									<button type="button" class="button remove-button<# if ( ! field.default ) { #> hidden<# } #>"></button>
478
									<button type="button" class="button upload-button" data-label="<?php esc_attr_e( 'Add File', 'kirki' ); ?>" data-alt-label="<?php esc_attr_e( 'Change File', 'kirki' ); ?>">
479
										<# if ( field.default ) { #>
480
											<?php esc_attr_e( 'Change File', 'kirki' ); ?>
481
										<# } else { #>
482
											<?php esc_attr_e( 'Add File', 'kirki' ); ?>
483
										<# } #>
484
									</button>
485
									<# if ( field.default.id ) { #>
486
										<input type="hidden" class="hidden-field" value="{{{ field.default.id }}}" data-field="{{{ field.id }}}" >
487
									<# } else { #>
488
										<input type="hidden" class="hidden-field" value="{{{ field.default }}}" data-field="{{{ field.id }}}" >
489
									<# } #>
490
								</div>
491
492
							<# } else if ( 'custom' === field.type ) { #>
493
494
								<# if ( field.label ) { #><span class="customize-control-title">{{ field.label }}</span><# } #>
495
								<# if ( field.description ) { #><span class="description customize-control-description">{{ field.description }}</span><# } #>
496
								<div data-field="{{{ field.id }}}">{{{ field.default }}}</div>
497
498
							<# } #>
499
500
						</div>
501
					<# }); #>
502
					<button type="button" class="button-link repeater-row-remove"><?php esc_attr_e( 'Remove', 'kirki' ); ?></button>
503
				</div>
504
			</li>
505
		</script>
506
		<?php
507
	}
508
509
	/**
510
	 * Validate row-labels.
511
	 *
512
	 * @access protected
513
	 * @since 3.0.0
514
	 * @param array $args {@see WP_Customize_Control::__construct}.
515
	 */
516
	protected function row_label( $args ) {
517
518
		// Validating args for row labels.
519
		if ( isset( $args['row_label'] ) && is_array( $args['row_label'] ) && ! empty( $args['row_label'] ) ) {
520
521
			// Validating row label type.
522
			if ( isset( $args['row_label']['type'] ) && ( 'text' === $args['row_label']['type'] || 'field' === $args['row_label']['type'] ) ) {
523
				$this->row_label['type'] = $args['row_label']['type'];
524
			}
525
526
			// Validating row label type.
527
			if ( isset( $args['row_label']['value'] ) && ! empty( $args['row_label']['value'] ) ) {
528
				$this->row_label['value'] = esc_attr( $args['row_label']['value'] );
529
			}
530
531
			// Validating row label field.
532
			if ( isset( $args['row_label']['field'] ) && ! empty( $args['row_label']['field'] ) && isset( $args['fields'][ esc_attr( $args['row_label']['field'] ) ] ) ) {
533
				$this->row_label['field'] = esc_attr( $args['row_label']['field'] );
534
			} else {
535
				// If from field is not set correctly, making sure standard is set as the type.
536
				$this->row_label['type'] = 'text';
537
			}
538
		}
539
	}
540
}
541