helper-functions.php ➔ cmb2_utils()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
ccs 3
cts 3
cp 1
crap 2
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 19 and the first side effect is on line 127.

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
 *
15
 * @since  2.0.0
16
 * @param  string $path Path to append
17
 * @return string        Directory with optional path appended
18
 */
19
function cmb2_dir( $path = '' ) {
20 25
	return CMB2_DIR . $path;
21
}
22
23
/**
24
 * Autoloads files with CMB2 classes when needed
25
 *
26
 * @since  1.0.0
27
 * @param  string $class_name Name of the class being requested
28
 */
29
function cmb2_autoload_classes( $class_name ) {
30 24
	if ( 0 !== strpos( $class_name, 'CMB2' ) ) {
31 1
		return;
32
	}
33
34 24
	$path = 'includes';
35
36 24
	if ( 'CMB2_Type' === $class_name || 0 === strpos( $class_name, 'CMB2_Type_' ) ) {
37 20
		$path .= '/types';
38 20
	}
39
40 24
	if ( 'CMB2_REST' === $class_name || 0 === strpos( $class_name, 'CMB2_REST_' ) ) {
41
		$path .= '/rest-api';
42
	}
43
44 24
	include_once( cmb2_dir( "$path/{$class_name}.php" ) );
45 24
}
46
47
/**
48
 * Get instance of the CMB2_Utils class
49
 *
50
 * @since  2.0.0
51
 * @return CMB2_Utils object CMB2 utilities class
52
 */
53
function cmb2_utils() {
54 1
	static $cmb2_utils;
55 1
	$cmb2_utils = $cmb2_utils ? $cmb2_utils : new CMB2_Utils();
56 1
	return $cmb2_utils;
57
}
58
59
/**
60
 * Get instance of the CMB2_Ajax class
61
 *
62
 * @since  2.0.0
63
 * @return CMB2_Ajax object CMB2 ajax class
64
 */
65
function cmb2_ajax() {
66 5
	return CMB2_Ajax::get_instance();
67
}
68
69
/**
70
 * Get instance of the CMB2_Option class for the passed metabox ID
71
 *
72
 * @since  2.0.0
73
 * @return CMB2_Option object Options class for setting/getting options for metabox
74
 */
75
function cmb2_options( $key ) {
76 14
	return CMB2_Options::get( $key );
77
}
78
79
/**
80
 * Get a cmb oEmbed. Handles oEmbed getting for non-post objects
81
 *
82
 * @since  2.0.0
83
 * @param  array $args Arguments. Accepts:
84
 *
85
 *       'url'         - URL to retrieve the oEmbed from,
86
 *       'object_id'   - $post_id,
87
 *       'object_type' - 'post',
88
 *       'oembed_args' - $embed_args, // array containing 'width', etc
89
 *       'field_id'    - false,
90
 *       'cache_key'   - false,
91
 *       'wp_error'    - true/false, // To return a wp_error object if no embed found.
92
 *
93
 * @return string        oEmbed string
94
 */
95
function cmb2_get_oembed( $args = array() ) {
96 1
	$oembed = cmb2_ajax()->get_oembed_no_edit( $args );
97
98
	// Send back our embed
99 1
	if ( $oembed['embed'] && $oembed['embed'] != $oembed['fallback'] ) {
100 1
		return '<div class="cmb2-oembed">' . $oembed['embed'] . '</div>';
101
	}
102
103
	$error = sprintf(
104
		/* translators: 1: results for. 2: link to codex.wordpress.org/Embeds */
105
		esc_html__( 'No oEmbed Results Found for %1$s. View more info at %2$s.', 'cmb2' ),
106
		$oembed['fallback'],
107
		'<a href="https://codex.wordpress.org/Embeds" target="_blank">codex.wordpress.org/Embeds</a>'
108
	);
109
110
	if ( isset( $args['wp_error'] ) && $args['wp_error'] ) {
111
		return new WP_Error( 'cmb2_get_oembed_result', $error, compact( 'oembed', 'args' ) );
112
	}
113
114
	// Otherwise, send back error info that no oEmbeds were found
115
	return '<p class="ui-state-error-text">' . $error . '</p>';
116
}
117
118
/**
119
 * Outputs the return of cmb2_get_oembed.
120
 *
121
 * @since  2.2.2
122
 * @see cmb2_get_oembed
123
 */
124
function cmb2_do_oembed( $args = array() ) {
125 1
	echo cmb2_get_oembed( $args );
126 1
}
127
add_action( 'cmb2_do_oembed', 'cmb2_do_oembed' );
128
129
/**
130
 * A helper function to get an option from a CMB2 options array
131
 *
132
 * @since  1.0.1
133
 * @param  string $option_key Option key
134
 * @param  string $field_id   Option array field key
135
 * @param  mixed  $default    Optional default fallback value
136
 * @return array               Options array or specific field
137
 */
138
function cmb2_get_option( $option_key, $field_id = '', $default = false ) {
139 2
	return cmb2_options( $option_key )->get( $field_id, $default );
140
}
141
142
/**
143
 * A helper function to update an option in a CMB2 options array
144
 *
145
 * @since  2.0.0
146
 * @param  string  $option_key Option key
147
 * @param  string  $field_id   Option array field key
148
 * @param  mixed   $value      Value to update data with
149
 * @param  boolean $single     Whether data should not be an array
150
 * @return boolean             Success/Failure
151
 */
152
function cmb2_update_option( $option_key, $field_id, $value, $single = true ) {
153 1
	if ( cmb2_options( $option_key )->update( $field_id, $value, false, $single ) ) {
154 1
		return cmb2_options( $option_key )->set();
155
	}
156
157
	return false;
158
}
159
160
/**
161
 * Get a CMB2 field object.
162
 *
163
 * @since  1.1.0
164
 * @param  array  $meta_box    Metabox ID or Metabox config array
165
 * @param  array  $field_id    Field ID or all field arguments
166
 * @param  int    $object_id   Object ID
167
 * @param  string $object_type Type of object being saved. (e.g., post, user, comment, or options-page).
168
 *                             Defaults to metabox object type.
169
 * @return CMB2_Field|null     CMB2_Field object unless metabox config cannot be found
170
 */
171
function cmb2_get_field( $meta_box, $field_id, $object_id = 0, $object_type = '' ) {
172
173 10
	$object_id = $object_id ? $object_id : get_the_ID();
174 10
	$cmb = $meta_box instanceof CMB2 ? $meta_box : cmb2_get_metabox( $meta_box, $object_id );
175
176 10
	if ( ! $cmb ) {
177
		return;
178
	}
179
180 10
	$cmb->object_type( $object_type ? $object_type : $cmb->mb_object_type() );
181
182 10
	return $cmb->get_field( $field_id );
183
}
184
185
/**
186
 * Get a field's value.
187
 *
188
 * @since  1.1.0
189
 * @param  array  $meta_box    Metabox ID or Metabox config array
190
 * @param  array  $field_id    Field ID or all field arguments
191
 * @param  int    $object_id   Object ID
192
 * @param  string $object_type Type of object being saved. (e.g., post, user, comment, or options-page).
193
 *                             Defaults to metabox object type.
194
 * @return mixed               Maybe escaped value
195
 */
196
function cmb2_get_field_value( $meta_box, $field_id, $object_id = 0, $object_type = '' ) {
197 1
	$field = cmb2_get_field( $meta_box, $field_id, $object_id, $object_type );
198 1
	return $field->escaped_value();
199
}
200
201
/**
202
 * Because OOP can be scary
203
 *
204
 * @since  2.0.2
205
 * @param  array $meta_box_config Metabox Config array
206
 * @return CMB2 object            Instantiated CMB2 object
207
 */
208
function new_cmb2_box( array $meta_box_config ) {
209 2
	return cmb2_get_metabox( $meta_box_config );
210
}
211
212
/**
213
 * Retrieve a CMB2 instance by the metabox ID
214
 *
215
 * @since  2.0.0
216
 * @param  mixed  $meta_box    Metabox ID or Metabox config array
217
 * @param  int    $object_id   Object ID
218
 * @param  string $object_type Type of object being saved. (e.g., post, user, comment, or options-page).
219
 *                             Defaults to metabox object type.
220
 * @return CMB2 object
221
 */
222
function cmb2_get_metabox( $meta_box, $object_id = 0, $object_type = '' ) {
223
224 34
	if ( $meta_box instanceof CMB2 ) {
225 1
		return $meta_box;
226
	}
227
228 34
	if ( is_string( $meta_box ) ) {
229 28
		$cmb = CMB2_Boxes::get( $meta_box );
230 28
	} else {
231
		// See if we already have an instance of this metabox
232 9
		$cmb = CMB2_Boxes::get( $meta_box['id'] );
233
		// If not, we'll initate a new metabox
234 9
		$cmb = $cmb ? $cmb : new CMB2( $meta_box, $object_id );
235
	}
236
237 34
	if ( $cmb && $object_id ) {
238 17
		$cmb->object_id( $object_id );
239 17
	}
240
241 34
	if ( $cmb && $object_type ) {
242 7
		$cmb->object_type( $object_type );
243 7
	}
244
245 34
	return $cmb;
246
}
247
248
/**
249
 * Returns array of sanitized field values from a metabox (without saving them)
250
 *
251
 * @since  2.0.3
252
 * @param  mixed $meta_box         Metabox ID or Metabox config array
253
 * @param  array $data_to_sanitize Array of field_id => value data for sanitizing (likely $_POST data).
254
 * @return mixed                   Array of sanitized values or false if no CMB2 object found
255
 */
256
function cmb2_get_metabox_sanitized_values( $meta_box, array $data_to_sanitize ) {
257 1
	$cmb = cmb2_get_metabox( $meta_box );
258 1
	return $cmb ? $cmb->get_sanitized_values( $data_to_sanitize ) : false;
259
}
260
261
/**
262
 * Retrieve a metabox form
263
 *
264
 * @since  2.0.0
265
 * @param  mixed $meta_box  Metabox config array or Metabox ID
266
 * @param  int   $object_id Object ID
267
 * @param  array $args      Optional arguments array
268
 * @return string             CMB2 html form markup
269
 */
270
function cmb2_get_metabox_form( $meta_box, $object_id = 0, $args = array() ) {
271
272 1
	$object_id = $object_id ? $object_id : get_the_ID();
273 1
	$cmb       = cmb2_get_metabox( $meta_box, $object_id );
274
275 1
	ob_start();
276
	// Get cmb form
277 1
	cmb2_print_metabox_form( $cmb, $object_id, $args );
278 1
	$form = ob_get_clean();
279
280 1
	return apply_filters( 'cmb2_get_metabox_form', $form, $object_id, $cmb );
281
}
282
283
/**
284
 * Display a metabox form & save it on submission
285
 *
286
 * @since  1.0.0
287
 * @param  mixed $meta_box  Metabox config array or Metabox ID
288
 * @param  int   $object_id Object ID
289
 * @param  array $args      Optional arguments array
290
 */
291
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...
292
293 1
	$object_id = $object_id ? $object_id : get_the_ID();
294 1
	$cmb = cmb2_get_metabox( $meta_box, $object_id );
295
296
	// if passing a metabox ID, and that ID was not found
297 1
	if ( ! $cmb ) {
298
		return;
299
	}
300
301 1
	$args = wp_parse_args( $args, array(
302 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>',
303 1
		'save_button' => esc_html__( 'Save', 'cmb2' ),
304 1
		'object_type' => $cmb->mb_object_type(),
305 1
		'cmb_styles'  => $cmb->prop( 'cmb_styles' ),
306 1
		'enqueue_js'  => $cmb->prop( 'enqueue_js' ),
307 1
	) );
308
309
	// Set object type explicitly (rather than trying to guess from context)
310 1
	$cmb->object_type( $args['object_type'] );
311
312
	// Save the metabox if it's been submitted
313
	// check permissions
314
	// @todo more hardening?
315
	if (
316 1
		$cmb->prop( 'save_fields' )
317
		// check nonce
318 1
		&& isset( $_POST['submit-cmb'], $_POST['object_id'], $_POST[ $cmb->nonce() ] )
319 1
		&& wp_verify_nonce( $_POST[ $cmb->nonce() ], $cmb->nonce() )
320 1
		&& $object_id && $_POST['object_id'] == $object_id
321 1
	) {
322
		$cmb->save_fields( $object_id, $cmb->object_type(), $_POST );
323
	}
324
325
	// Enqueue JS/CSS
326 1
	if ( $args['cmb_styles'] ) {
327 1
		CMB2_hookup::enqueue_cmb_css();
328 1
	}
329
330 1
	if ( $args['enqueue_js'] ) {
331 1
		CMB2_hookup::enqueue_cmb_js();
332 1
	}
333
334 1
	$form_format = apply_filters( 'cmb2_get_metabox_form_format', $args['form_format'], $object_id, $cmb );
335
336 1
	$format_parts = explode( '%3$s', $form_format );
337
338
	// Show cmb form
339 1
	printf( $format_parts[0], $cmb->cmb_id, $object_id );
0 ignored issues
show
Documentation introduced by
The property $cmb_id is declared protected in CMB2_Base. Since you implemented __get(), maybe consider adding a @property or @property-read annotation. This makes it easier for IDEs to provide auto-completion.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
340 1
	$cmb->show_form();
341
342 1
	if ( isset( $format_parts[1] ) && $format_parts[1] ) {
343 1
		printf( str_ireplace( '%4$s', '%1$s', $format_parts[1] ), $args['save_button'] );
344 1
	}
345
346 1
}
347
348
/**
349
 * Display a metabox form (or optionally return it) & save it on submission
350
 *
351
 * @since  1.0.0
352
 * @param  mixed $meta_box  Metabox config array or Metabox ID
353
 * @param  int   $object_id Object ID
354
 * @param  array $args      Optional arguments array
355
 */
356
function cmb2_metabox_form( $meta_box, $object_id = 0, $args = array() ) {
357
	if ( ! isset( $args['echo'] ) || $args['echo'] ) {
358
		cmb2_print_metabox_form( $meta_box, $object_id, $args );
359
	} else {
360
		return cmb2_get_metabox_form( $meta_box, $object_id, $args );
361
	}
362
}
363
364
if ( ! function_exists( 'date_create_from_format' ) ) {
365
366
	/**
367
	 * Reimplementation of DateTime::createFromFormat for PHP < 5.3. :(
368
	 * Borrowed from http://stackoverflow.com/questions/5399075/php-datetimecreatefromformat-in-5-2
369
	 *
370
	 * @param $date_format
371
	 * @param $date_value
372
	 *
373
	 * @return DateTime
374
	 */
375
	function date_create_from_format( $date_format, $date_value ) {
376
377
		$schedule_format = str_replace(
378
			array( 'M', 'Y', 'm', 'd', 'H', 'i', 'a' ),
379
			array( '%b', '%Y', '%m', '%d', '%H', '%M', '%p' ),
380
			$date_format
381
		);
382
383
		/*
384
		 * %Y, %m and %d correspond to date()'s Y m and d.
385
		 * %I corresponds to H, %M to i and %p to a
386
		 */
387
		$parsed_time = strptime( $date_value, $schedule_format );
388
389
		$ymd = sprintf(
390
			/*
391
			 * This is a format string that takes six total decimal
392
			 * arguments, then left-pads them with zeros to either
393
			 * 4 or 2 characters, as needed
394
			 */
395
			'%04d-%02d-%02d %02d:%02d:%02d',
396
			$parsed_time['tm_year'] + 1900,  // This will be "111", so we need to add 1900.
397
			$parsed_time['tm_mon'] + 1,      // This will be the month minus one, so we add one.
398
			$parsed_time['tm_mday'],
399
			$parsed_time['tm_hour'],
400
			$parsed_time['tm_min'],
401
			$parsed_time['tm_sec']
402
		);
403
404
		return new DateTime( $ymd );
405
	}
406
}// End if().
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% 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...
407