Completed
Push — trunk ( 295b81...e98a4d )
by Justin
11s
created

helper-functions.php ➔ cmb2_print_metabox_form()   C

Complexity

Conditions 12
Paths 34

Size

Total Lines 56
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 30
CRAP Score 12.1081
Metric Value
cc 12
eloc 28
nc 34
nop 3
dl 0
loc 56
ccs 30
cts 33
cp 0.9091
crap 12.1081
rs 6.7092

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
/**
3
 * CMB2 Helper Functions
4
 *
5
 * @category  WordPress_Plugin
6
 * @package   CMB2
7
 * @author    WebDevStudios
8
 * @license   GPL-2.0+
9
 * @link      http://webdevstudios.com
10
 */
11
12
/**
13
 * Helper function to provide directory path to CMB2
14
 * @since  2.0.0
15
 * @param  string  $path Path to append
16
 * @return string        Directory with optional path appended
17
 */
18
function cmb2_dir( $path = '' ) {
19 25
	return CMB2_DIR . $path;
20
}
21
22
/**
23
 * Autoloads files with CMB2 classes when needed
24
 * @since  1.0.0
25
 * @param  string $class_name Name of the class being requested
26
 */
27
function cmb2_autoload_classes( $class_name ) {
28 24
	if ( 0 !== strpos( $class_name, 'CMB2' ) ) {
29 1
		return;
30
	}
31
32 24
	$path = 'includes';
33
34 24
	if ( 'CMB2_Type' === $class_name || 0 === strpos( $class_name, 'CMB2_Type_' ) ) {
35 21
		$path .= '/types';
36 21
	}
37
38 24
	include_once( cmb2_dir( "$path/{$class_name}.php" ) );
39 24
}
40
41
/**
42
 * Get instance of the CMB2_Utils class
43
 * @since  2.0.0
44
 * @return CMB2_Utils object CMB2 utilities class
45
 */
46
function cmb2_utils() {
47 64
	static $cmb2_utils;
48 64
	$cmb2_utils = $cmb2_utils ? $cmb2_utils : new CMB2_Utils();
49 64
	return $cmb2_utils;
50
}
51
52
/**
53
 * Get instance of the CMB2_Ajax class
54
 * @since  2.0.0
55
 * @return CMB2_Ajax object CMB2 utilities class
56
 */
57
function cmb2_ajax() {
58 4
	return CMB2_Ajax::get_instance();
59
}
60
61
/**
62
 * Get instance of the CMB2_Option class for the passed metabox ID
63
 * @since  2.0.0
64
 * @return CMB2_Option object Options class for setting/getting options for metabox
65
 */
66
function cmb2_options( $key ) {
67 11
	return CMB2_Options::get( $key );
68
}
69
70
/**
71
 * Get a cmb oEmbed. Handles oEmbed getting for non-post objects
72
 * @since  2.0.0
73
 * @param  array   $args Arguments. Accepts:
74
 *
75
 *         'url'         - URL to retrieve the oEmbed from,
76
 *         'object_id'   - $post_id,
77
 *         'object_type' - 'post',
78
 *         'oembed_args' - $embed_args, // array containing 'width', etc
79
 *         'field_id'    - false,
80
 *         'cache_key'   - false,
81
 *
82
 * @return string        oEmbed string
83
 */
84
function cmb2_get_oembed( $args = array() ) {
85 2
	return cmb2_ajax()->get_oembed( $args );
86
}
87
88
/**
89
 * A helper function to get an option from a CMB2 options array
90
 * @since  1.0.1
91
 * @param  string  $option_key Option key
92
 * @param  string  $field_id   Option array field key
93
 * @param  mixed   $default    Optional default fallback value
94
 * @return array               Options array or specific field
95
 */
96
function cmb2_get_option( $option_key, $field_id = '', $default = false ) {
97 2
	return cmb2_options( $option_key )->get( $field_id, $default );
98
}
99
100
/**
101
 * A helper function to update an option in a CMB2 options array
102
 * @since  2.0.0
103
 * @param  string  $option_key Option key
104
 * @param  string  $field_id   Option array field key
105
 * @param  mixed   $value      Value to update data with
106
 * @param  boolean $single     Whether data should not be an array
107
 * @return boolean             Success/Failure
108
 */
109
function cmb2_update_option( $option_key, $field_id, $value, $single = true ) {
110 1
	if ( cmb2_options( $option_key )->update( $field_id, $value, false, $single ) ) {
111 1
		return cmb2_options( $option_key )->set();
112
	}
113
114
	return false;
115
}
116
117
/**
118
 * Get a CMB2 field object.
119
 * @since  1.1.0
120
 * @param  array  $meta_box    Metabox ID or Metabox config array
121
 * @param  array  $field_id    Field ID or all field arguments
122
 * @param  int    $object_id   Object ID
123
 * @param  string $object_type Type of object being saved. (e.g., post, user, comment, or options-page).
124
 *                             Defaults to metabox object type.
125
 * @return CMB2_Field|null     CMB2_Field object unless metabox config cannot be found
126
 */
127
function cmb2_get_field( $meta_box, $field_id, $object_id = 0, $object_type = '' ) {
128
129 10
	$object_id = $object_id ? $object_id : get_the_ID();
130 10
	$cmb = $meta_box instanceof CMB2 ? $meta_box : cmb2_get_metabox( $meta_box, $object_id );
131
132 10
	if ( ! $cmb ) {
133
		return;
134
	}
135
136 10
	$cmb->object_type( $object_type ? $object_type : $cmb->mb_object_type() );
0 ignored issues
show
Security Bug introduced by
It seems like $object_type ? $object_t... $cmb->mb_object_type() can also be of type false; however, CMB2::object_type() does only seem to accept string, did you maybe forget to handle an error condition?
Loading history...
137
138 10
	return $cmb->get_field( $field_id );
139
}
140
141
/**
142
 * Get a field's value.
143
 * @since  1.1.0
144
 * @param  array  $meta_box    Metabox ID or Metabox config array
145
 * @param  array  $field_id    Field ID or all field arguments
146
 * @param  int    $object_id   Object ID
147
 * @param  string $object_type Type of object being saved. (e.g., post, user, comment, or options-page).
148
 *                             Defaults to metabox object type.
149
 * @return mixed               Maybe escaped value
150
 */
151
function cmb2_get_field_value( $meta_box, $field_id, $object_id = 0, $object_type = '' ) {
152 1
	$field = cmb2_get_field( $meta_box, $field_id, $object_id, $object_type );
153 1
	return $field->escaped_value();
154
}
155
156
/**
157
 * Because OOP can be scary
158
 * @since  2.0.2
159
 * @param  array $meta_box_config Metabox Config array
160
 * @return CMB2 object            Instantiated CMB2 object
161
 */
162
function new_cmb2_box( array $meta_box_config ) {
163 2
	return cmb2_get_metabox( $meta_box_config );
164
}
165
166
/**
167
 * Retrieve a CMB2 instance by the metabox ID
168
 * @since  2.0.0
169
 * @param  mixed  $meta_box    Metabox ID or Metabox config array
170
 * @param  int    $object_id   Object ID
171
 * @param  string $object_type Type of object being saved. (e.g., post, user, comment, or options-page).
172
 *                             Defaults to metabox object type.
173
 * @return CMB2 object
174
 */
175
function cmb2_get_metabox( $meta_box, $object_id = 0, $object_type = '' ) {
176
177 32
	if ( $meta_box instanceof CMB2 ) {
178 1
		return $meta_box;
179
	}
180
181 32
	if ( is_string( $meta_box ) ) {
182 26
		$cmb = CMB2_Boxes::get( $meta_box );
183 26
	} else {
184
		// See if we already have an instance of this metabox
185 9
		$cmb = CMB2_Boxes::get( $meta_box['id'] );
186
		// If not, we'll initate a new metabox
187 9
		$cmb = $cmb ? $cmb : new CMB2( $meta_box, $object_id );
188
	}
189
190 32
	if ( $cmb && $object_id ) {
191 17
		$cmb->object_id( $object_id );
192 17
	}
193
194 32
	if ( $cmb && $object_type ) {
195 7
		$cmb->object_type( $object_type );
196 7
	}
197
198 32
	return $cmb;
199
}
200
201
/**
202
 * Returns array of sanitized field values from a metabox (without saving them)
203
 * @since  2.0.3
204
 * @param  mixed $meta_box         Metabox ID or Metabox config array
205
 * @param  array $data_to_sanitize Array of field_id => value data for sanitizing (likely $_POST data).
206
 * @return mixed                   Array of sanitized values or false if no CMB2 object found
207
 */
208
function cmb2_get_metabox_sanitized_values( $meta_box, array $data_to_sanitize ) {
209 1
	$cmb = cmb2_get_metabox( $meta_box );
210 1
	return $cmb ? $cmb->get_sanitized_values( $data_to_sanitize ) : false;
211
}
212
213
/**
214
 * Retrieve a metabox form
215
 * @since  2.0.0
216
 * @param  mixed   $meta_box  Metabox config array or Metabox ID
217
 * @param  int     $object_id Object ID
218
 * @param  array   $args      Optional arguments array
219
 * @return string             CMB2 html form markup
220
 */
221
function cmb2_get_metabox_form( $meta_box, $object_id = 0, $args = array() ) {
222
223 1
	$object_id = $object_id ? $object_id : get_the_ID();
224 1
	$cmb       = cmb2_get_metabox( $meta_box, $object_id );
225
226 1
	ob_start();
227
	// Get cmb form
228 1
	cmb2_print_metabox_form( $cmb, $object_id, $args );
229 1
	$form = ob_get_contents();
230 1
	ob_end_clean();
231
232 1
	return apply_filters( 'cmb2_get_metabox_form', $form, $object_id, $cmb );
233
}
234
235
/**
236
 * Display a metabox form & save it on submission
237
 * @since  1.0.0
238
 * @param  mixed   $meta_box  Metabox config array or Metabox ID
239
 * @param  int     $object_id Object ID
240
 * @param  array   $args      Optional arguments array
241
 */
242
function cmb2_print_metabox_form( $meta_box, $object_id = 0, $args = array() ) {
0 ignored issues
show
Coding Style introduced by
cmb2_print_metabox_form uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
243
244 1
	$object_id = $object_id ? $object_id : get_the_ID();
245 1
	$cmb = cmb2_get_metabox( $meta_box, $object_id );
246
247
	// if passing a metabox ID, and that ID was not found
248 1
	if ( ! $cmb ) {
249
		return;
250
	}
251
252 1
	$args = wp_parse_args( $args, array(
253 1
		'form_format' => '<form class="cmb-form" method="post" id="%1$s" enctype="multipart/form-data" encoding="multipart/form-data"><input type="hidden" name="object_id" value="%2$s">%3$s<input type="submit" name="submit-cmb" value="%4$s" class="button-primary"></form>',
254 1
		'save_button' => __( 'Save', 'cmb2' ),
255 1
		'object_type' => $cmb->mb_object_type(),
256 1
		'cmb_styles'  => $cmb->prop( 'cmb_styles' ),
257 1
		'enqueue_js'  => $cmb->prop( 'enqueue_js' ),
258 1
	) );
259
260
	// Set object type explicitly (rather than trying to guess from context)
261 1
	$cmb->object_type( $args['object_type'] );
262
263
	// Save the metabox if it's been submitted
264
	// check permissions
265
	// @todo more hardening?
266
	if (
267 1
		$cmb->prop( 'save_fields' )
268
		// check nonce
269 1
		&& isset( $_POST['submit-cmb'], $_POST['object_id'], $_POST[ $cmb->nonce() ] )
270 1
		&& wp_verify_nonce( $_POST[ $cmb->nonce() ], $cmb->nonce() )
271 1
		&& $object_id && $_POST['object_id'] == $object_id
272 1
	) {
273
		$cmb->save_fields( $object_id, $cmb->object_type(), $_POST );
274
	}
275
276
	// Enqueue JS/CSS
277 1
	if ( $args['cmb_styles'] ) {
278 1
		CMB2_hookup::enqueue_cmb_css();
279 1
	}
280
281 1
	if ( $args['enqueue_js'] ) {
282 1
		CMB2_hookup::enqueue_cmb_js();
283 1
	}
284
285 1
	$form_format = apply_filters( 'cmb2_get_metabox_form_format', $args['form_format'], $object_id, $cmb );
286
287 1
	$format_parts = explode( '%3$s', $form_format );
288
289
	// Show cmb form
290 1
	printf( $format_parts[0], $cmb->cmb_id, $object_id );
291 1
	$cmb->show_form();
292
293 1
	if ( isset( $format_parts[1] ) && $format_parts[1] ) {
294 1
		printf( str_ireplace( '%4$s', '%1$s', $format_parts[1] ), $args['save_button'] );
295 1
	}
296
297 1
}
298
299
/**
300
 * Display a metabox form (or optionally return it) & save it on submission
301
 * @since  1.0.0
302
 * @param  mixed   $meta_box  Metabox config array or Metabox ID
303
 * @param  int     $object_id Object ID
304
 * @param  array   $args      Optional arguments array
305
 */
306
function cmb2_metabox_form( $meta_box, $object_id = 0, $args = array() ) {
307
	if ( ! isset( $args['echo'] ) || $args['echo'] ) {
308
		cmb2_print_metabox_form( $meta_box, $object_id, $args );
309
	} else {
310
		return cmb2_get_metabox_form( $meta_box, $object_id, $args );
311
	}
312
}
313
314
if ( ! function_exists( 'date_create_from_format' ) ) {
315
316
	/**
317
	 * Reimplementation of DateTime::createFromFormat for PHP < 5.3. :(
318
	 * Borrowed from http://stackoverflow.com/questions/5399075/php-datetimecreatefromformat-in-5-2
319
	 *
320
	 * @param $date_format
321
	 * @param $date_value
322
	 *
323
	 * @return DateTime
324
	 */
325
	function date_create_from_format( $date_format, $date_value ) {
326
327
		$schedule_format = str_replace(
328
			array( 'M', 'Y', 'm', 'd', 'H', 'i', 'a' ),
329
			array('%b', '%Y', '%m', '%d', '%H', '%M', '%p' ),
330
			$date_format
331
		);
332
333
		/*
334
		 * %Y, %m and %d correspond to date()'s Y m and d.
335
		 * %I corresponds to H, %M to i and %p to a
336
		 */
337
		$parsed_time = strptime( $date_value, $schedule_format );
338
339
		$ymd = sprintf(
340
			/*
341
			 * This is a format string that takes six total decimal
342
			 * arguments, then left-pads them with zeros to either
343
			 * 4 or 2 characters, as needed
344
			 */
345
			'%04d-%02d-%02d %02d:%02d:%02d',
346
			$parsed_time['tm_year'] + 1900,  // This will be "111", so we need to add 1900.
347
			$parsed_time['tm_mon'] + 1,      // This will be the month minus one, so we add one.
348
			$parsed_time['tm_mday'],
349
			$parsed_time['tm_hour'],
350
			$parsed_time['tm_min'],
351
			$parsed_time['tm_sec']
352
		);
353
354
		return new DateTime($ymd);
355
	}
356
}
357