Completed
Push — master ( 3695fa...6fb9d6 )
by Mike
02:26
created

Metaboxes::random_metabox_content()   D

Complexity

Conditions 36
Paths 106

Size

Total Lines 170
Code Lines 79

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 2
Metric Value
cc 36
eloc 79
c 5
b 0
f 2
nc 106
nop 3
dl 0
loc 170
rs 4.2102

How to fix   Long Method    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
namespace testContent;
3
4
/**
5
 * Class for handling CMB data
6
 *
7
 * @package    WordPress
8
 * @subpackage Evans
9
 * @author     Old Town Media
10
 */
11
class Metaboxes{
12
13
	/**
14
	 * Decide which cmb library to try and loop to get our metaboxes.
15
	 *
16
	 * Due to supporting multiple CMB libraries, we need to check which library
17
	 * is used on our site and then run the appropriate function. Currently
18
	 * supported libraries are CMB2 & Custom Metaboxes and Fields.
19
	 *
20
	 * @see get_cmb2_metaboxes, get_cmb1_metaboxes
21
	 *
22
	 * @param string $slug Post Type slug ID.
23
	 * @return array Fields to fill in for our post object.
24
	 */
25
	public function get_metaboxes( $slug ){
26
		$cmb2_fields = $cmb_fields = $acf_fields = array();
27
28
		// CMB2
29
		if ( class_exists( 'CMB2', false ) ) {
30
			$cmb2_fields = $this->get_cmb2_metaboxes( $slug );
31
		}
32
33
		// Custom Metaboxes and Fields (CMB1)
34
		if ( class_exists( 'cmb_Meta_Box', false ) ) {
35
			$cmb_fields = $this->get_cmb1_metaboxes( $slug );
36
		}
37
38
		// Advanced Custom Fields (ACF Free)
39
		if ( class_exists( 'acf', false ) ) {
40
			$acf_fields = $this->get_acf_free_metaboxes( $slug );
41
		}
42
43
		// Return our array
44
		return array_merge( $cmb2_fields, $cmb_fields, $acf_fields );
45
46
	}
47
48
49
	private function get_acf_free_metaboxes( $slug ){
50
51
		$fields = array();
52
53
		// This damn plugin. Is. A. Freaking. Nightmare.
54
		$fieldsets = $this->get_all_acf_field_groups();
55
56
		// Return empty array if there are no fieldsets at all
57
		if ( empty( $fieldsets ) ){
58
			return $fields;
59
		}
60
61
		// Loop through each fieldset for possible matches
62
		foreach ( $fieldsets as $fieldset ){
63
64
			if ( $this->is_acf_field_in_post_type( $slug, $fieldset ) ){
65
66
				// If this is the first group of fields, simply set the value
67
				// Else, merge this group with the previous one
68
				if ( empty( $fields ) ){
69
					$fields = $fieldset->fields;
70
				} else {
71
					$fields = array_merge( $fields, $fieldset->fields );
72
				}
73
74
			}
75
76
		}
77
78
		return $fields;
79
80
	}
81
82
83
	private function is_acf_field_in_post_type( $slug, $fieldset ){
84
85
		// Make sure we have something to parse
86
		if ( empty( $fieldset ) ){
87
			return false;
88
		}
89
90
		// Loop through the rules to check for post type matches
91
		foreach ( $fieldset->rules as $rule ){
92
			if ( $rule['param'] === 'post_type' && $rule['value'] === $slug ){
93
				return true;
94
			}
95
		}
96
97
		// Everything passed, yay!
98
		return false;
99
100
	}
101
102
103
	private function get_all_acf_field_groups(){
104
		$info = $rules = $fields = array();
105
106
		$args = array(
107
			'post_type'		=> 'acf',
108
			'posts_per_page'=> 500
109
		);
110
111
		$objects = new \WP_Query( $args );
112
113
		if ( $objects->have_posts() ) :
114
			while ( $objects->have_posts() ) : $objects->the_post();
115
116
				$data = get_metadata( 'post', get_the_id() );
117
118
				foreach ( $data['rule'] as $rule ){
119
					$rules[] = unserialize( $rule );
120
				}
121
122
				foreach ( $data as $key => $value ){
123
					if ( substr( $key, 0, 6 ) == 'field_' ) :
124
						$field_detail = unserialize( $value[0] );
125
						$fields[] = array(
126
							'key'	 => $field_detail['key'],
127
							'type'	 => $field_detail['type'],
128
							'name'	 => $field_detail['label'],
129
							'id'	 => $field_detail['name'],
130
							'source' =>'acf'
131
						);
132
					endif;
133
				}
134
135
				$info[] = (object) array(
136
					'rules'		=> $rules,
137
					'fields'	=> $fields
138
				);
139
140
			endwhile;
141
		endif;
142
143
		return $info;
144
145
	}
146
147
148
	/**
149
	 * Gets all CMB2 custom metaboxes associated with a post type.
150
	 *
151
	 * Loops through all custom metabox fields registered with CMB2 and
152
	 * looks through them for matches on the given post type ID. Returns a single
153
	 * array of all boxes associated with the post type.
154
	 *
155
	 * @access private
156
	 *
157
	 * @see cmb2_meta_boxes
158
	 *
159
	 * @param string $slug a custom post type ID.
160
	 * @return array Array of fields.
161
	 */
162
	private function get_cmb2_metaboxes( $slug ){
163
164
		$fields = array();
165
166
		// Get all metaboxes from CMB2 library
167
		$all_metaboxes = apply_filters( 'cmb2_meta_boxes', array() );
168
169
		// Loop through all possible sets of metaboxes added the old way
170
		foreach ( $all_metaboxes as $metabox_array ){
171
172
			// If the custom post type ID matches this set of fields, set & stop
173
			if ( in_array( $slug, $metabox_array['object_types'] ) ) {
174
175
				// If this is the first group of fields, simply set the value
176
				// Else, merge this group with the previous one
177
				if ( empty( $fields ) ){
178
					$fields = $metabox_array['fields'];
179
				} else {
180
					$fields = array_merge( $fields, $metabox_array['fields'] );
181
				}
182
			}
183
184
		}
185
186
		// Loop through all metaboxes added the new way
187
		foreach ( \CMB2_Boxes::get_all() as $cmb ) {
188
189
			// Create the default
190
			$match = false;
191
192
			// Establish correct cmb types
193
			if ( is_string( $cmb->meta_box['object_types'] ) ){
194
				if ( $cmb->meta_box['object_types'] == $slug ){
195
					$match = true;
196
				}
197
			} else {
198
				if ( in_array( $slug, $cmb->meta_box['object_types'] ) ){
199
					$match = true;
200
				}
201
			}
202
203
			if ( $match !== true ){
204
				continue;
205
			}
206
207
			if ( empty( $fields ) ){
208
				$fields = $cmb->meta_box['fields'];
209
			} else {
210
				$fields = array_merge( $fields, $cmb->meta_box['fields'] );
211
			}
212
213
		}
214
215
		return $fields;
216
217
	}
218
219
220
	/**
221
	 * Gets all CMB1 custom metaboxes associated with a post type.
222
	 *
223
	 * Loops through all custom metabox fields registered with CMB2 and
224
	 * looks through them for matches on the given post type ID. Returns a single
225
	 * array of all boxes associated with the post type.
226
	 *
227
	 * @access private
228
	 *
229
	 * @see cmb_meta_boxes
230
	 *
231
	 * @param string $slug a custom post type ID.
232
	 * @return array Array of fields.
233
	 */
234
	private function get_cmb1_metaboxes( $slug ){
235
236
		$fields = array();
237
238
		// Get all metaboxes from CMB2 library
239
		$all_metaboxes = apply_filters( 'cmb_meta_boxes', array() );
240
241
		// Loop through all possible sets of metaboxes
242
		foreach ( $all_metaboxes as $metabox_array ){
243
244
			// If the custom post type ID matches this set of fields, set & stop
245
			if ( in_array( $slug, $metabox_array['pages'] ) ) {
246
247
				// If this is the first group of fields, simply set the value
248
				// Else, merge this group with the previous one
249
				if ( empty( $fields ) ){
250
					$fields = $metabox_array['fields'];
251
				} else {
252
					$fields = array_merge( $fields, $metabox_array['fields'] );
253
				}
254
			}
255
256
		}
257
258
		return $fields;
259
260
	}
261
262
263
	/**
264
	 * Assigns the proper testing data to a custom metabox.
265
	 *
266
	 * Swaps through the possible types of CMB2 supported fields and
267
	 * insert the appropriate data based on type & id.
268
	 * Some types are not yet supported due to low frequency of use.
269
	 *
270
	 * @see TestContent, add_post_meta
271
	 *
272
	 * @param int $post_id Single post ID.
273
	 * @param array $cmb custom metabox array from CMB2.
274
	 */
275
	public function random_metabox_content( $post_id, $cmb, $connected ){
276
		$value = '';
277
278
		// First check that our post ID & cmb array aren't empty
279
		if ( empty( $cmb ) || empty( $post_id ) ){
280
			return;
281
		}
282
283
		// Fetch the appropriate type of data and return
284
		switch( $cmb['type'] ){
285
286
			case 'text':
287
			case 'text_small':
288
			case 'text_medium':
289
290
				// If phone is in the id, fetch a phone #
291
				if ( stripos( $cmb['id'], 'phone' ) ){
292
					$value = TestContent::phone();
293
294
				// If email is in the id, fetch an email address
295
				} elseif ( stripos( $cmb['id'], 'email' ) ){
296
					$value = TestContent::email();
297
298
				// If time is in the id, fetch a time string
299
				} elseif ( stripos( $cmb['id'], 'time' ) ){
300
					$value = TestContent::time();
301
302
				// Otherwise, just a random text string
303
				} else {
304
					$value = TestContent::title( rand( 10, 50 ) );
305
				}
306
307
				break;
308
309
			case 'text_url':
310
311
				$value = TestContent::link();
312
313
				break;
314
315
			case 'text_email':
316
317
				$value = TestContent::email();
318
319
				break;
320
321
			case 'text_time':
322
323
				$value = TestContent::time();
324
325
				break;
326
327
			case 'select_timezone':
328
329
				$value = TestContent::timezone();
330
331
				break;
332
333
			case 'text_date':
334
335
				$value = TestContent::date( 'm/d/Y' );
336
337
				break;
338
339
			case 'text_date_timestamp':
340
			case 'text_datetime_timestamp':
341
342
				$value = TestContent::date( 'U' );
343
344
				break;
345
346
			// case 'text_datetime_timestamp_timezone': break;
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
347
348
			case 'text_money':
349
350
				$value = rand( 0, 100000 );
351
352
				break;
353
354
			case 'test_colorpicker':
355
356
				$value = '#' . str_pad( dechex( mt_rand( 0, 0xFFFFFF ) ), 6, '0', STR_PAD_LEFT );
357
358
				break;
359
360
			case 'textarea':
361
			case 'textarea_small':
362
			case 'textarea_code':
363
364
				$value = TestContent::plain_text();
365
366
				break;
367
368
			case 'select':
369
			case 'radio_inline':
370
			case 'radio':
371
372
				// Grab a random item out of the array and return the key
373
				$new_val = array_slice( $cmb['options'], rand( 0, count( $cmb['options'] ) ), 1 );
374
				$value = key( $new_val );
375
376
				break;
377
378
			// case 'taxonomy_radio': break;
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
379
			// case 'taxonomy_select': break;
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
380
			// case 'taxonomy_multicheck': break;
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
381
382
			case 'checkbox':
383
384
				// 50/50 odds of being turned on
385
				if ( rand( 0, 1 ) == 1 ){
386
					$value = 'on';
387
				}
388
389
				break;
390
391
			case 'multicheck':
392
393
				$new_option = array();
394
395
				// Loop through each of our options
396
				foreach ( $cmb['options'] as $key => $value ){
397
398
					// 50/50 chance of being included
399
					if ( rand( 0, 1 ) ){
400
						$new_option[] = $key;
401
					}
402
403
				}
404
405
				$value = $new_option;
406
407
				break;
408
409
			case 'wysiwyg':
410
411
				$value = TestContent::paragraphs();
412
413
				break;
414
415
			case 'file':
416
417
				if ( true == $connected ){
418
					$value = TestContent::image( $post_id );
419
				}
420
421
				break;
422
423
			// case 'file_list': break;
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
424
425
			case 'oembed':
426
427
				$value = TestContent::oembed();
428
429
				break;
430
431
		}
432
433
		// Value must exist to attempt to insert
434
		if ( ! empty( $value ) && ! is_wp_error( $value ) ){
435
436
			$this->update_meta( $post_id, $value, $cmb );
437
438
		// If we're dealing with a WP Error object, just return the message for debugging
439
		} elseif ( is_wp_error( $value ) ){
440
			error_log( $value->get_error_message() );
441
			return $value->get_error_message();
442
		}
443
444
	} // end random_metabox_content
445
446
447
	private function update_meta( $post_id, $value, $cmb ){
448
449
		$type 	= $cmb['type'];
450
		$id		= $cmb['id'];
451
		$value = apply_filters( "tc_{$type}_metabox", $value );	// Filter by metabox type
452
		$value = apply_filters( "tc_{$id}_metabox", $value ); // Filter by metabox ID
453
454
		// Files must be treated separately - they use the attachment ID
455
		// & url of media for separate cmb values.
456
		if ( $cmb['type'] != 'file' ){
457
			add_post_meta( $post_id, $cmb['id'], $value, true );
458
		} else {
459
			add_post_meta( $post_id, $cmb['id'].'_id', $value, true );
460
			add_post_meta( $post_id, $cmb['id'], wp_get_attachment_url( $value ), true );
461
		}
462
463
		// Add extra, redundant meta. Because, why not have rows for the price of one?
464
		if ( $cmb['source'] === 'acf' ){
465
			add_post_meta( $post_id, '_' . $cmb['id'], $cmb['key'], true );
466
		}
467
468
	}
469
470
}
471