Completed
Pull Request — trunk (#541)
by Justin
28:03 queued 25:22
created

helper-functions.php ➔ cmb2_autoload_classes()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 6.027

Importance

Changes 0
Metric Value
cc 6
eloc 9
nc 5
nop 1
dl 0
loc 17
ccs 10
cts 11
cp 0.9091
crap 6.027
rs 8.8571
c 0
b 0
f 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 18 and the first side effect is on line 120.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
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 28
	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 27
	if ( 0 !== strpos( $class_name, 'CMB2' ) ) {
29
		return;
30
	}
31
32 27
	$path = 'includes';
33
34 27
	if ( 'CMB2_Type' === $class_name || 0 === strpos( $class_name, 'CMB2_Type_' ) ) {
35 22
		$path .= '/types';
36 22
	}
37
38 27
	if ( 'CMB2_REST' === $class_name || 0 === strpos( $class_name, 'CMB2_REST_' ) ) {
39 1
		$path .= '/rest-api';
40 1
	}
41
42 27
	include_once( cmb2_dir( "$path/{$class_name}.php" ) );
43 27
}
44
45
/**
46
 * Get instance of the CMB2_Utils class
47
 * @since  2.0.0
48
 * @return CMB2_Utils object CMB2 utilities class
49
 */
50
function cmb2_utils() {
51 1
	static $cmb2_utils;
52 1
	$cmb2_utils = $cmb2_utils ? $cmb2_utils : new CMB2_Utils();
53 1
	return $cmb2_utils;
54
}
55
56
/**
57
 * Get instance of the CMB2_Ajax class
58
 * @since  2.0.0
59
 * @return CMB2_Ajax object CMB2 ajax class
60
 */
61
function cmb2_ajax() {
62 5
	return CMB2_Ajax::get_instance();
63
}
64
65
/**
66
 * Get instance of the CMB2_Option class for the passed metabox ID
67
 * @since  2.0.0
68
 * @return CMB2_Option object Options class for setting/getting options for metabox
69
 */
70
function cmb2_options( $key ) {
71 10
	return CMB2_Options::get( $key );
72
}
73
74
/**
75
 * Get a cmb oEmbed. Handles oEmbed getting for non-post objects
76
 * @since  2.0.0
77
 * @param  array   $args Arguments. Accepts:
78
 *
79
 *         'url'         - URL to retrieve the oEmbed from,
80
 *         'object_id'   - $post_id,
81
 *         'object_type' - 'post',
82
 *         'oembed_args' - $embed_args, // array containing 'width', etc
83
 *         'field_id'    - false,
84
 *         'cache_key'   - false,
85
 *         'wp_error'    - true/false, // To return a wp_error object if no embed found.
86
 *
87
 * @return string        oEmbed string
88
 */
89
function cmb2_get_oembed( $args = array() ) {
90 1
	$oembed = cmb2_ajax()->get_oembed_no_edit( $args );
91
92
	// Send back our embed
93 1
	if ( $oembed['embed'] && $oembed['embed'] != $oembed['fallback'] ) {
94 1
		return '<div class="cmb2-oembed">' . $oembed['embed'] . '</div>';
95
	}
96
97
	$error = sprintf(
98
		/* translators: 1: results for. 2: link to codex.wordpress.org/Embeds */
99
		esc_html__( 'No oEmbed Results Found for %1$s. View more info at %2$s.', 'cmb2' ),
100
		$oembed['fallback'],
101
		'<a href="https://codex.wordpress.org/Embeds" target="_blank">codex.wordpress.org/Embeds</a>'
102
	);
103
104
	if ( isset( $args['wp_error'] ) && $args['wp_error'] ) {
105
		return new WP_Error( 'cmb2_get_oembed_result', $wp_error, compact( 'oembed', 'args' ) );
0 ignored issues
show
Bug introduced by
The variable $wp_error does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
106
	}
107
108
	// Otherwise, send back error info that no oEmbeds were found
109
	return '<p class="ui-state-error-text">' . $error . '</p>';
110
}
111
112
/**
113
 * Outputs the return of cmb2_get_oembed.
114
 * @since  2.2.2
115
 * @see cmb2_get_oembed
116
 */
117
function cmb2_do_oembed( $args = array() ) {
118 1
	echo cmb2_get_oembed( $args );
119 1
}
120
add_action( 'cmb2_do_oembed', 'cmb2_do_oembed' );
121
122
/**
123
 * A helper function to get an option from a CMB2 options array
124
 * @since  1.0.1
125
 * @param  string  $option_key Option key
126
 * @param  string  $field_id   Option array field key
127
 * @param  mixed   $default    Optional default fallback value
128
 * @return array               Options array or specific field
129
 */
130
function cmb2_get_option( $option_key, $field_id = '', $default = false ) {
131 2
	return cmb2_options( $option_key )->get( $field_id, $default );
132
}
133
134
/**
135
 * A helper function to update an option in a CMB2 options array
136
 * @since  2.0.0
137
 * @param  string  $option_key Option key
138
 * @param  string  $field_id   Option array field key
139
 * @param  mixed   $value      Value to update data with
140
 * @param  boolean $single     Whether data should not be an array
141
 * @return boolean             Success/Failure
142
 */
143
function cmb2_update_option( $option_key, $field_id, $value, $single = true ) {
144 1
	if ( cmb2_options( $option_key )->update( $field_id, $value, false, $single ) ) {
145 1
		return cmb2_options( $option_key )->set();
146
	}
147
148
	return false;
149
}
150
151
/**
152
 * Get a CMB2 field object.
153
 * @since  1.1.0
154
 * @param  array  $meta_box    Metabox ID or Metabox config array
155
 * @param  array  $field_id    Field ID or all field arguments
156
 * @param  int    $object_id   Object ID
157
 * @param  string $object_type Type of object being saved. (e.g., post, user, comment, or options-page).
158
 *                             Defaults to metabox object type.
159
 * @return CMB2_Field|null     CMB2_Field object unless metabox config cannot be found
160
 */
161
function cmb2_get_field( $meta_box, $field_id, $object_id = 0, $object_type = '' ) {
162
163 10
	$object_id = $object_id ? $object_id : get_the_ID();
164 10
	$cmb = $meta_box instanceof CMB2 ? $meta_box : cmb2_get_metabox( $meta_box, $object_id );
165
166 10
	if ( ! $cmb ) {
167
		return;
168
	}
169
170 10
	$cmb->object_type( $object_type ? $object_type : $cmb->mb_object_type() );
171
172 10
	return $cmb->get_field( $field_id );
173
}
174
175
/**
176
 * Get a field's value.
177
 * @since  1.1.0
178
 * @param  array  $meta_box    Metabox ID or Metabox config array
179
 * @param  array  $field_id    Field ID or all field arguments
180
 * @param  int    $object_id   Object ID
181
 * @param  string $object_type Type of object being saved. (e.g., post, user, comment, or options-page).
182
 *                             Defaults to metabox object type.
183
 * @return mixed               Maybe escaped value
184
 */
185
function cmb2_get_field_value( $meta_box, $field_id, $object_id = 0, $object_type = '' ) {
186 1
	$field = cmb2_get_field( $meta_box, $field_id, $object_id, $object_type );
187 1
	return $field->escaped_value();
188
}
189
190
/**
191
 * Because OOP can be scary
192
 * @since  2.0.2
193
 * @param  array $meta_box_config Metabox Config array
194
 * @return CMB2 object            Instantiated CMB2 object
195
 */
196
function new_cmb2_box( array $meta_box_config ) {
197 2
	return cmb2_get_metabox( $meta_box_config );
198
}
199
200
/**
201
 * Retrieve a CMB2 instance by the metabox ID
202
 * @since  2.0.0
203
 * @param  mixed  $meta_box    Metabox ID or Metabox config array
204
 * @param  int    $object_id   Object ID
205
 * @param  string $object_type Type of object being saved. (e.g., post, user, comment, or options-page).
206
 *                             Defaults to metabox object type.
207
 * @return CMB2 object
208
 */
209
function cmb2_get_metabox( $meta_box, $object_id = 0, $object_type = '' ) {
210
211 34
	if ( $meta_box instanceof CMB2 ) {
212 1
		return $meta_box;
213
	}
214
215 34
	if ( is_string( $meta_box ) ) {
216 28
		$cmb = CMB2_Boxes::get( $meta_box );
217 28
	} else {
218
		// See if we already have an instance of this metabox
219 9
		$cmb = CMB2_Boxes::get( $meta_box['id'] );
220
		// If not, we'll initate a new metabox
221 9
		$cmb = $cmb ? $cmb : new CMB2( $meta_box, $object_id );
222
	}
223
224 34
	if ( $cmb && $object_id ) {
225 17
		$cmb->object_id( $object_id );
226 17
	}
227
228 34
	if ( $cmb && $object_type ) {
229 7
		$cmb->object_type( $object_type );
230 7
	}
231
232 34
	return $cmb;
233
}
234
235
/**
236
 * Returns array of sanitized field values from a metabox (without saving them)
237
 * @since  2.0.3
238
 * @param  mixed $meta_box         Metabox ID or Metabox config array
239
 * @param  array $data_to_sanitize Array of field_id => value data for sanitizing (likely $_POST data).
240
 * @return mixed                   Array of sanitized values or false if no CMB2 object found
241
 */
242
function cmb2_get_metabox_sanitized_values( $meta_box, array $data_to_sanitize ) {
243 1
	$cmb = cmb2_get_metabox( $meta_box );
244 1
	return $cmb ? $cmb->get_sanitized_values( $data_to_sanitize ) : false;
245
}
246
247
/**
248
 * Retrieve a metabox form
249
 * @since  2.0.0
250
 * @param  mixed   $meta_box  Metabox config array or Metabox ID
251
 * @param  int     $object_id Object ID
252
 * @param  array   $args      Optional arguments array
253
 * @return string             CMB2 html form markup
254
 */
255
function cmb2_get_metabox_form( $meta_box, $object_id = 0, $args = array() ) {
256
257 1
	$object_id = $object_id ? $object_id : get_the_ID();
258 1
	$cmb       = cmb2_get_metabox( $meta_box, $object_id );
259
260 1
	ob_start();
261
	// Get cmb form
262 1
	cmb2_print_metabox_form( $cmb, $object_id, $args );
263 1
	$form = ob_get_contents();
264 1
	ob_end_clean();
265
266 1
	return apply_filters( 'cmb2_get_metabox_form', $form, $object_id, $cmb );
267
}
268
269
/**
270
 * Display a metabox form & save it on submission
271
 * @since  1.0.0
272
 * @param  mixed   $meta_box  Metabox config array or Metabox ID
273
 * @param  int     $object_id Object ID
274
 * @param  array   $args      Optional arguments array
275
 */
276
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...
277
278 1
	$object_id = $object_id ? $object_id : get_the_ID();
279 1
	$cmb = cmb2_get_metabox( $meta_box, $object_id );
280
281
	// if passing a metabox ID, and that ID was not found
282 1
	if ( ! $cmb ) {
283
		return;
284
	}
285
286 1
	$args = wp_parse_args( $args, array(
287 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>',
288 1
		'save_button' => esc_html__( 'Save', 'cmb2' ),
289 1
		'object_type' => $cmb->mb_object_type(),
290 1
		'cmb_styles'  => $cmb->prop( 'cmb_styles' ),
291 1
		'enqueue_js'  => $cmb->prop( 'enqueue_js' ),
292 1
	) );
293
294
	// Set object type explicitly (rather than trying to guess from context)
295 1
	$cmb->object_type( $args['object_type'] );
296
297
	// Save the metabox if it's been submitted
298
	// check permissions
299
	// @todo more hardening?
300
	if (
301 1
		$cmb->prop( 'save_fields' )
302
		// check nonce
303 1
		&& isset( $_POST['submit-cmb'], $_POST['object_id'], $_POST[ $cmb->nonce() ] )
304 1
		&& wp_verify_nonce( $_POST[ $cmb->nonce() ], $cmb->nonce() )
305 1
		&& $object_id && $_POST['object_id'] == $object_id
306 1
	) {
307
		$cmb->save_fields( $object_id, $cmb->object_type(), $_POST );
308
	}
309
310
	// Enqueue JS/CSS
311 1
	if ( $args['cmb_styles'] ) {
312 1
		CMB2_hookup::enqueue_cmb_css();
313 1
	}
314
315 1
	if ( $args['enqueue_js'] ) {
316 1
		CMB2_hookup::enqueue_cmb_js();
317 1
	}
318
319 1
	$form_format = apply_filters( 'cmb2_get_metabox_form_format', $args['form_format'], $object_id, $cmb );
320
321 1
	$format_parts = explode( '%3$s', $form_format );
322
323
	// Show cmb form
324 1
	printf( $format_parts[0], $cmb->cmb_id, $object_id );
325 1
	$cmb->show_form();
326
327 1
	if ( isset( $format_parts[1] ) && $format_parts[1] ) {
328 1
		printf( str_ireplace( '%4$s', '%1$s', $format_parts[1] ), $args['save_button'] );
329 1
	}
330
331 1
}
332
333
/**
334
 * Display a metabox form (or optionally return it) & save it on submission
335
 * @since  1.0.0
336
 * @param  mixed   $meta_box  Metabox config array or Metabox ID
337
 * @param  int     $object_id Object ID
338
 * @param  array   $args      Optional arguments array
339
 */
340
function cmb2_metabox_form( $meta_box, $object_id = 0, $args = array() ) {
341
	if ( ! isset( $args['echo'] ) || $args['echo'] ) {
342
		cmb2_print_metabox_form( $meta_box, $object_id, $args );
343
	} else {
344
		return cmb2_get_metabox_form( $meta_box, $object_id, $args );
345
	}
346
}
347
348
if ( ! function_exists( 'date_create_from_format' ) ) {
349
350
	/**
351
	 * Reimplementation of DateTime::createFromFormat for PHP < 5.3. :(
352
	 * Borrowed from http://stackoverflow.com/questions/5399075/php-datetimecreatefromformat-in-5-2
353
	 *
354
	 * @param $date_format
355
	 * @param $date_value
356
	 *
357
	 * @return DateTime
358
	 */
359
	function date_create_from_format( $date_format, $date_value ) {
360
361
		$schedule_format = str_replace(
362
			array( 'M', 'Y', 'm', 'd', 'H', 'i', 'a' ),
363
			array('%b', '%Y', '%m', '%d', '%H', '%M', '%p' ),
364
			$date_format
365
		);
366
367
		/*
368
		 * %Y, %m and %d correspond to date()'s Y m and d.
369
		 * %I corresponds to H, %M to i and %p to a
370
		 */
371
		$parsed_time = strptime( $date_value, $schedule_format );
372
373
		$ymd = sprintf(
374
			/*
375
			 * This is a format string that takes six total decimal
376
			 * arguments, then left-pads them with zeros to either
377
			 * 4 or 2 characters, as needed
378
			 */
379
			'%04d-%02d-%02d %02d:%02d:%02d',
380
			$parsed_time['tm_year'] + 1900,  // This will be "111", so we need to add 1900.
381
			$parsed_time['tm_mon'] + 1,      // This will be the month minus one, so we add one.
382
			$parsed_time['tm_mday'],
383
			$parsed_time['tm_hour'],
384
			$parsed_time['tm_min'],
385
			$parsed_time['tm_sec']
386
		);
387
388
		return new DateTime($ymd);
389
	}
390
}
391