Completed
Push — issues/1132 ( 716ec5 )
by Ravinder
40:09 queued 19:53
created

formatting.php ➔ give_check_variable()   D

Complexity

Conditions 20
Paths 24

Size

Total Lines 43
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 20
eloc 29
nc 24
nop 4
dl 0
loc 43
rs 4.8819
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
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 25 and the first side effect is on line 14.

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
 * Formatting functions for taking care of proper number formats and such
4
 *
5
 * @package     Give
6
 * @subpackage  Functions/Formatting
7
 * @copyright   Copyright (c) 2016, WordImpress
8
 * @license     https://opensource.org/licenses/gpl-license GNU Public License
9
 * @since       1.0
10
 */
11
12
// Exit if accessed directly.
13
if ( ! defined( 'ABSPATH' ) ) {
14
	exit;
15
}
16
17
18
/**
19
 * Get decimal count
20
 *
21
 * @since 1.6
22
 *
23
 * @return mixed
24
 */
25
function give_get_price_decimals() {
26
	return apply_filters( 'give_sanitize_amount_decimals', give_get_option( 'number_decimals', 0 ) );
27
}
28
29
/**
30
 * Get thousand separator
31
 *
32
 * @since 1.6
33
 *
34
 * @return mixed
35
 */
36
function give_get_price_thousand_separator() {
37
	return give_get_option( 'thousands_separator', ',' );
38
}
39
40
/**
41
 * Get decimal separator
42
 *
43
 * @since 1.6
44
 *
45
 * @return mixed
46
 */
47
function give_get_price_decimal_separator() {
48
	return give_get_option( 'decimal_separator', '.' );
49
}
50
51
/**
52
 * Sanitize Amount
53
 *
54
 * Returns a sanitized amount by stripping out thousands separators.
55
 *
56
 * @since      1.0
57
 *
58
 * @param  int|float|string $number     Expects either a float or a string with a decimal separator only (no thousands)
59
 * @param  int|bool         $dp         Number of decimals
60
 * @param  bool             $trim_zeros From end of string
61
 *
62
 * @return string $amount Newly sanitized amount
63
 */
64
function give_sanitize_amount( $number, $dp = false, $trim_zeros = false ) {
65
66
	// Bailout.
67
	if ( empty( $number ) ) {
68
		return $number;
69
	}
70
71
	// Remove slash from amount.
72
	// If thousand or decimal separator is set to ' then in $_POST or $_GET param we will get an escaped number.
73
	// To prevent notices and warning remove slash from amount/number.
74
	$number = wp_unslash( $number );
75
76
	$thousand_separator = give_get_price_thousand_separator();
77
78
	$locale   = localeconv();
79
	$decimals = array( give_get_price_decimal_separator(), $locale['decimal_point'], $locale['mon_decimal_point'] );
80
81
	// Remove locale from string
82
	if ( ! is_float( $number ) ) {
83
		$number = str_replace( $decimals, '.', $number );
84
	}
85
86
	// Remove thousand amount formatting if amount has.
87
	// This condition use to add backward compatibility to version before 1.6, because before version 1.6 we were saving formatted amount to db.
88
	// Do not replace thousand separator from price if it is same as decimal separator, because it will be already replace by above code.
89
	if ( ! in_array( $thousand_separator, $decimals ) && ( false !== strpos( $number, $thousand_separator ) ) ) {
90
		$number = str_replace( $thousand_separator, '', $number );
91
	} elseif ( in_array( $thousand_separator, $decimals ) ) {
92
		$number = preg_replace( '/\.(?=.*\.)/', '', $number );
93
	}
94
95
	// Remove non numeric entity before decimal separator.
96
	$number     = preg_replace( '/[^0-9\.]/', '', $number );
97
	$default_dp = give_get_price_decimals();
98
99
	// Reset negative amount to zero.
100
	if ( 0 > $number ) {
101
		$number = number_format( 0, $default_dp, '.' );
102
	}
103
104
	// If number does not have decimal then add number of decimals to it.
105
	if (
106
		false === strpos( $number, '.' )
107
		|| ( $default_dp > strlen( substr( $number, strpos( $number, '.' ) + 1 ) ) )
108
	) {
109
		$number = number_format( $number, $default_dp, '.', '' );
110
	}
111
112
	// Format number by custom number of decimals.
113
	if ( false !== $dp ) {
114
		$dp     = intval( is_bool( $dp ) ? $default_dp : $dp );
115
		$dp     = apply_filters( 'give_sanitize_amount_decimals', $dp, $number );
116
		$number = number_format( floatval( $number ), $dp, '.', '' );
117
	}
118
119
	// Trim zeros.
120
	if ( $trim_zeros && strstr( $number, '.' ) ) {
121
		$number = rtrim( rtrim( $number, '0' ), '.' );
122
	}
123
124
	return apply_filters( 'give_sanitize_amount', $number );
125
}
126
127
/**
128
 * Returns a nicely formatted amount.
129
 *
130
 * @since 1.0
131
 *
132
 * @param string $amount   Price amount to format
133
 * @param bool   $decimals Whether or not to use decimals. Useful when set to false for non-currency numbers.
134
 *
135
 * @return string $amount   Newly formatted amount or Price Not Available
136
 */
137
function give_format_amount( $amount, $decimals = true ) {
138
	$thousands_sep = give_get_option( 'thousands_separator', ',' );
139
	$decimal_sep   = give_get_option( 'decimal_separator', '.' );
140
141
	if ( empty( $amount ) ) {
142
		$amount = 0;
143
	} else {
144
		// Sanitize amount before formatting.
145
		$amount = give_sanitize_amount( $amount );
146
	}
147
148
	$decimals = $decimals ? give_get_price_decimals() : 0;
149
150
	$formatted = number_format( $amount, $decimals, $decimal_sep, $thousands_sep );
151
152
	return apply_filters( 'give_format_amount', $formatted, $amount, $decimals, $decimal_sep, $thousands_sep );
153
}
154
155
156
/**
157
 * Get human readable amount.
158
 *
159
 * Note: This function only support large number formatting from million to trillion
160
 *
161
 * @since 1.6
162
 *
163
 * @use   give_get_price_thousand_separator Get thousand separator.
164
 *
165
 * @param string $amount formatted amount number.
166
 *
167
 * @return float|string  formatted amount number with large number names.
168
 */
169
function give_human_format_large_amount( $amount ) {
170
171
	// Get thousand separator.
172
	$thousands_sep = give_get_price_thousand_separator();
173
174
	// Sanitize amount.
175
	$sanitize_amount = give_sanitize_amount( $amount );
176
177
	// Explode amount to calculate name of large numbers.
178
	$amount_array = explode( $thousands_sep, $amount );
179
180
	// Calculate amount parts count.
181
	$amount_count_parts = count( $amount_array );
182
183
	// Human format amount (default).
184
	$human_format_amount = $amount;
185
186
	// Calculate large number formatted amount.
187
	if ( 4 < $amount_count_parts ) {
188
		$human_format_amount = sprintf( esc_html__( '%s trillion', 'give' ), round( ( $sanitize_amount / 1000000000000 ), 2 ) );
189
	} elseif ( 3 < $amount_count_parts ) {
190
		$human_format_amount = sprintf( esc_html__( '%s billion', 'give' ), round( ( $sanitize_amount / 1000000000 ), 2 ) );
191
	} elseif ( 2 < $amount_count_parts ) {
192
		$human_format_amount = sprintf( esc_html__( '%s million', 'give' ), round( ( $sanitize_amount / 1000000 ), 2 ) );
193
	}
194
195
	return apply_filters( 'give_human_format_large_amount', $human_format_amount, $amount, $sanitize_amount );
196
}
197
198
/**
199
 * Returns a nicely formatted amount with custom decimal separator.
200
 *
201
 * @since 1.0
202
 *
203
 * @param int|float|string $amount Formatted or sanitized price
204
 * @param int|bool         $dp     number of decimals
205
 *
206
 * @return string $amount Newly formatted amount or Price Not Available
207
 */
208
function give_format_decimal( $amount, $dp = false ) {
209
	$decimal_separator = give_get_price_decimal_separator();
210
	$formatted_amount  = give_sanitize_amount( $amount, $dp );
211
212
	if ( false !== strpos( $formatted_amount, '.' ) ) {
213
		$formatted_amount = str_replace( '.', $decimal_separator, $formatted_amount );
214
	}
215
216
	return apply_filters( 'give_format_decimal', $formatted_amount, $amount, $decimal_separator );
217
}
218
219
/**
220
 * Formats the currency display
221
 *
222
 * @since 1.0
223
 *
224
 * @param string $price
225
 * @param string $currency
226
 * @param bool   $decode_currency
227
 *
228
 * @return mixed|string
229
 */
230
function give_currency_filter( $price = '', $currency = '', $decode_currency = false ) {
231
232
	if ( empty( $currency ) ) {
233
		$currency = give_get_currency();
234
	}
235
236
	$position = give_get_option( 'currency_position', 'before' );
237
238
	$negative = $price < 0;
239
240
	if ( $negative ) {
241
		// Remove proceeding "-".
242
		$price = substr( $price, 1 );
243
	}
244
245
	$symbol = give_currency_symbol( $currency );
246
247
	switch ( $currency ) :
248
		case 'GBP' :
249
		case 'BRL' :
250
		case 'EUR' :
251
		case 'USD' :
252
		case 'AUD' :
253
		case 'CAD' :
254
		case 'HKD' :
255
		case 'MXN' :
256
		case 'NZD' :
257
		case 'SGD' :
258
		case 'JPY' :
259
		case 'THB' :
260
		case 'INR' :
261
		case 'RIAL' :
262
		case 'TRY' :
263
		case 'RUB' :
264
		case 'SEK' :
265
		case 'PLN' :
266
		case 'PHP' :
267
		case 'TWD' :
268
		case 'MYR' :
269
		case 'CZK' :
270
		case 'DKK' :
271
		case 'HUF' :
272
		case 'ILS' :
273
		case 'MAD' :
274
		case 'KRW' :
275
		case 'ZAR' :
276
			$formatted = ( 'before' === $position ? $symbol . $price : $price . $symbol );
277
			break;
278
		case 'NOK' :
279
			$formatted = ( 'before' === $position ? $symbol . ' ' . $price : $price . ' ' . $symbol );
280
			break;
281
		default :
282
			$formatted = ( 'before' === $position ? $currency . ' ' . $price : $price . ' ' . $currency );
283
			break;
284
	endswitch;
285
286
	/**
287
	 * Filter formatted amount with currency
288
	 *
289
	 * Filter name depends upon current value of currency and currency position.
290
	 * For example :
291
	 *           if currency is USD and currency position is before then
292
	 *           filter name will be give_usd_currency_filter_before
293
	 *
294
	 *           and if currency is USD and currency position is after then
295
	 *           filter name will be give_usd_currency_filter_after
296
	 */
297
	$formatted = apply_filters( 'give_' . strtolower( $currency ) . "_currency_filter_{$position}", $formatted, $currency, $price );
298
299
	if ( $negative ) {
300
		// Prepend the minus sign before the currency sign.
301
		$formatted = '-' . $formatted;
302
	}
303
304
	return ( ! $decode_currency ? $formatted : html_entity_decode( $formatted ) );
305
}
306
307
/**
308
 * Set the number of decimal places per currency
309
 *
310
 * @since 1.0
311
 * @since 1.6 $decimals parameter removed from function params
312
 * *
313
 * @return int $decimals
314
 */
315
function give_currency_decimal_filter() {
316
317
	remove_filter( 'give_sanitize_amount_decimals', 'give_currency_decimal_filter' );
318
319
	// Set default number of decimals.
320
	$decimals = give_get_price_decimals();
321
322
	add_filter( 'give_sanitize_amount_decimals', 'give_currency_decimal_filter' );
323
324
	// Get number of decimals with backward compatibility ( version < 1.6 )
325
	if ( 1 <= func_num_args() ) {
326
		$decimals = ( false === func_get_arg( 0 ) ? $decimals : absint( func_get_arg( 0 ) ) );
327
	}
328
329
	$currency = give_get_currency();
330
331
	switch ( $currency ) {
332
		case 'RIAL' :
333
		case 'JPY' :
334
		case 'TWD' :
335
		case 'HUF' :
336
337
			$decimals = 0;
338
			break;
339
	}
340
341
	return apply_filters( 'give_currency_decimal_count', $decimals, $currency );
342
}
343
344
add_filter( 'give_sanitize_amount_decimals', 'give_currency_decimal_filter' );
345
add_filter( 'give_format_amount_decimals', 'give_currency_decimal_filter' );
346
347
348
/**
349
 * Get date format string on basis of given context.
350
 *
351
 * @since 1.7
352
 *
353
 * @param  string $date_context Date format context name.
354
 *
355
 * @return string                  Date format string
356
 */
357
function give_date_format( $date_context = '' ) {
358
	/**
359
	 * Filter the date context
360
	 *
361
	 * You can add your own date context or use already exist context.
362
	 * For example:
363
	 *    add_filter( 'give_date_format_contexts', 'add_new_date_contexts' );
364
	 *    function add_new_date_contexts( $date_format_contexts ) {
365
	 *        // You can add single context like this $date_format_contexts['checkout'] = 'F j, Y';
366
	 *        // Instead add multiple date context at once.
367
	 *        $new_date_format_contexts = array(
368
	 *            'checkout' => 'F j, Y',
369
	 *            'report'   => 'Y-m-d',
370
	 *            'email'    => 'm/d/Y',
371
	 *        );
372
	 *
373
	 *       // Merge date contexts array only if you are adding multiple date contexts at once otherwise return  $date_format_contexts.
374
	 *       return array_merge( $new_date_format_contexts, $date_format_contexts );
375
	 *
376
	 *    }
377
	 */
378
	$date_format_contexts = apply_filters( 'give_date_format_contexts', array() );
379
380
	// Set date format to default date format.
381
	$date_format = get_option( 'date_format' );
382
383
	// Update date format if we have non empty date format context array and non empty date format string for that context.
384
	if ( $date_context && ! empty( $date_format_contexts ) && array_key_exists( $date_context, $date_format_contexts ) ) {
385
		$date_format = ! empty( $date_format_contexts[ $date_context ] )
386
			? $date_format_contexts[ $date_context ]
387
			: $date_format;
388
	}
389
390
	return apply_filters( 'give_date_format', $date_format );
391
}
392
393
/**
394
 * Get cache key.
395
 *
396
 * @since  1.7
397
 * @deprecated 1.8.7 You can access this function from Give_Cache.
398
 *
399
 * @param  string $action     Cache key prefix.
400
 * @param array  $query_args Query array.
401
 *
402
 * @return string
403
 */
404
function give_get_cache_key( $action, $query_args ) {
405
	return Give_Cache::get_key( $action, $query_args );
406
}
407
408
/**
409
 * Clean variables using sanitize_text_field. Arrays are cleaned recursively.
410
 * Non-scalar values are ignored.
411
 *
412
 * @since  1.8
413
 *
414
 * @param  string|array $var
415
 *
416
 * @return string|array
417
 */
418
function give_clean( $var ) {
419
	if ( is_array( $var ) ) {
420
		return array_map( 'give_clean', $var );
421
	} else {
422
		return is_scalar( $var ) ? sanitize_text_field( $var ) : $var;
423
	}
424
}
425
426
/**
427
 * Transforms php.ini notation for numbers (like '2M') to an integer.
428
 *
429
 * @since 1.8
430
 *
431
 * @param $size
432
 *
433
 * @return int
0 ignored issues
show
Documentation introduced by
Should the return type not be integer|double|string?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
434
 */
435
function give_let_to_num( $size ) {
436
	$l   = substr( $size, - 1 );
437
	$ret = substr( $size, 0, - 1 );
438
	switch ( strtoupper( $l ) ) {
439
		case 'P':
440
			$ret *= 1024;
441
		case 'T':
442
			$ret *= 1024;
443
		case 'G':
444
			$ret *= 1024;
445
		case 'M':
446
			$ret *= 1024;
447
		case 'K':
448
			$ret *= 1024;
449
	}
450
451
	return $ret;
452
}
453
454
/**
455
 * Verify nonce.
456
 *
457
 * @since 1.8
458
 *
459
 * @param        $nonce
460
 * @param int   $action
461
 * @param array $wp_die_args
462
 */
463
function give_validate_nonce( $nonce, $action = - 1, $wp_die_args = array() ) {
464
465
	$default_wp_die_args = array(
466
		'message' => esc_html__( 'Nonce verification has failed.', 'give' ),
467
		'title'   => esc_html__( 'Error', 'give' ),
468
		'args'    => array( 'response' => 403 ),
469
	);
470
471
	$wp_die_args = wp_parse_args( $wp_die_args, $default_wp_die_args );
472
473
	if ( ! wp_verify_nonce( $nonce, $action ) ) {
474
		wp_die(
475
			$wp_die_args['message'],
476
			$wp_die_args['title'],
477
			$wp_die_args['args']
478
		);
479
	}
480
}
481
482
/**
483
 * Check variable and get default or valid value.
484
 *
485
 * Helper function to check if a variable is set, empty, etc.
486
 *
487
 * @since 1.8
488
 *
489
 * @param                   $variable
490
 * @param string (optional) $conditional    default value: isset
491
 * @param bool (optional)   $default        default value: false
492
 * @param string (optional) $array_key_name default value: false
493
 *
494
 * @return mixed
495
 */
496
function give_check_variable( $variable, $conditional = '', $default = false, $array_key_name = '' ) {
497
	// Get value from array if array key non empty.
498
	if( empty( $array_key_name ) ) {
499
		switch ( $conditional ) {
500
			case 'isset_empty':
501
				$variable = ( isset( $variable ) && ! empty( $variable ) ) ? $variable : $default;
502
				break;
503
504
			case 'empty':
505
				$variable = ! empty( $variable ) ? $variable : $default;
506
				break;
507
508
			case 'null':
509
				$variable = ! is_null( $variable ) ? $variable : $default;
510
				break;
511
512
			default:
513
				$variable = isset( $variable ) ? $variable : $default;
514
		}
515
	} else {
516
		$isset = array_key_exists( $array_key_name, $variable );
517
518
		switch ( $conditional ) {
519
			case 'isset_empty':
520
				$variable = ( $isset && ! empty( $variable[ $array_key_name ] ) ) ? $variable[ $array_key_name ] : $default;
521
				break;
522
523
			case 'empty':
524
				$variable = ! empty( $variable[ $array_key_name ] ) ? $variable[ $array_key_name ] : $default;
525
				break;
526
527
			case 'null':
528
				$variable = $isset && ! is_null( $variable[ $array_key_name ] ) ? $variable[ $array_key_name ] : $default;
529
				break;
530
531
			default:
532
				$variable = $isset && isset( $variable[ $array_key_name ] ) ? $variable[ $array_key_name ] : $default;
533
		}
534
	}
535
536
	return $variable;
537
538
}
539