Test Failed
Pull Request — master (#2225)
by Devin
04:40
created

formatting.php ➔ give_format_amount()   D

Complexity

Conditions 14
Paths 208

Size

Total Lines 79
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 210

Importance

Changes 0
Metric Value
cc 14
eloc 44
nc 208
nop 2
dl 0
loc 79
ccs 0
cts 0
cp 0
crap 210
rs 4.6121
c 0
b 0
f 0

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
 * 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
 * Get Currency Formatting Settings for each donation.
19
 *
20
 * @param int|string $id_or_currency_code Donation ID or Currency code.
21
 *
22
 * @since 1.8.15
23
 *
24
 * @return mixed
25
 */
26
function give_get_currency_formatting_settings( $id_or_currency_code = null ) {
27
	$give_options = give_get_settings();
28
	$setting      = array();
29 52
30 52
	if ( ! empty( $id_or_currency_code ) ) {
31 52
		$currencies   = give_get_currencies('all');
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
Coding Style introduced by
Expected 1 spaces before closing bracket; 0 found
Loading history...
32
33
		// Set default formatting setting only if currency not set as global currency.
34 52
35
		if( is_string( $id_or_currency_code ) && ( $id_or_currency_code !== $give_options['currency'] ) && array_key_exists( $id_or_currency_code, $currencies ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
36
			$setting = $currencies[ $id_or_currency_code ]['setting'];
37
		}elseif ( is_numeric( $id_or_currency_code ) && 'give_payment' === get_post_type( $id_or_currency_code ) ) {
38
			$donation_meta = give_get_meta( $id_or_currency_code, '_give_payment_meta', true );
39
40
			if (
41
				! empty( $donation_meta['currency'] ) &&
42 52
				$give_options['currency'] !== $donation_meta['currency']
43
			) {
44
				$setting = $currencies[ $donation_meta['currency'] ]['setting'];
45
			}
46 52
		}
47
	}
48
49
	if ( empty( $setting ) ) {
50 52
		// Set thousand separator.
51 52
		$thousand_separator = isset( $give_options['thousands_separator'] ) ? $give_options['thousands_separator'] : ',';
52 52
		$thousand_separator = empty( $thousand_separator ) ? ' ' : $thousand_separator;
53
54 52
		// Set decimal separator.
55
		$default_decimal_separators = array(
56
			'.' => ',',
57
			',' => '.',
58 52
		);
59
60
		$default_decimal_separator = in_array( $thousand_separator, $default_decimal_separators ) ?
61
			$default_decimal_separators[ $thousand_separator ] :
62
			'.';
63
64
		$decimal_separator = ! empty( $give_options['decimal_separator'] ) ? $give_options['decimal_separator'] : $default_decimal_separator;
65
66
		$setting = array(
67
			'currency_position'   => give_get_option( 'currency_position', 'before' ),
68
			'thousands_separator' => $thousand_separator,
69
			'decimal_separator'   => $decimal_separator,
70
			'number_decimals'     => give_get_option( 'number_decimals', 0 ),
71
		);
72
	}
73 43
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
74 43
75
	/**
76
	 * Filter the currency formatting setting.
77 43
	 *
78
	 * @since 1.8.15
79
	 */
80
	return apply_filters( 'give_get_currency_formatting_settings', $setting, $id_or_currency_code );
81
}
82
83
/**
84 43
 * Get decimal count
85
 *
86
 * @since 1.6
87
 *
88
 * @param int|string $id_or_currency_code
89 43
 *
90
 * @return mixed
91
 */
92 View Code Duplication
function give_get_price_decimals( $id_or_currency_code = null ) {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
93
	// Set currency on basis of donation id.
94
	if( empty( $id_or_currency_code ) ){
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
95
		$id_or_currency_code = give_get_currency();
96
	}
97
	
98
	$number_of_decimals = 0;
99 43
100
	if( ! give_is_zero_based_currency( $id_or_currency_code ) ){
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
101
		$setting = give_get_currency_formatting_settings( $id_or_currency_code );
102
		$number_of_decimals = $setting['number_decimals'];
103 43
	}
104 2
105 2
	/**
106
	 * Filter the number of decimals
107 43
	 *
108
	 * @since 1.6
109 43
	 */
110
	return apply_filters( 'give_sanitize_amount_decimals', $number_of_decimals, $id_or_currency_code );
111 43
}
112
113
/**
114
 * Get thousand separator
115
 *
116
 * @param int|string $id_or_currency_code
117
 *
118
 * @since 1.6
119
 *
120
 * @return mixed
121
 */
122
function give_get_price_thousand_separator( $id_or_currency_code = null ) {
123
	$setting = give_get_currency_formatting_settings( $id_or_currency_code );
124
125
	/**
126
	 * Filter the thousand separator
127
	 *
128
	 * @since 1.6
129
	 */
130
	return apply_filters( 'give_get_price_thousand_separator', $setting['thousands_separator'], $id_or_currency_code );
131
}
132
133
/**
134
 * Get decimal separator
135
 *
136
 * @param string $id_or_currency_code
137
 *
138
 * @since 1.6
139
 *
140
 * @return mixed
141
 */
142
function give_get_price_decimal_separator( $id_or_currency_code = null ) {
143
	$setting = give_get_currency_formatting_settings( $id_or_currency_code );
144
145
	/**
146 45
	 * Filter the thousand separator
147 45
	 *
148 45
	 * @since 1.6
149
	 */
150 45
	return apply_filters( 'give_get_price_decimal_separator', $setting['decimal_separator'], $id_or_currency_code );
151
}
152 45
153
154 45
/**
155
 * Sanitize Amount before saving to database
156
 *
157
 * @since      1.8.12
158 45
 *
159
 * @param  int|float|string $number Expects either a float or a string with a decimal separator only (no thousands)
160 45
 *
161
 * @return string $amount Newly sanitized amount
162 45
 */
163 45
function give_sanitize_amount_for_db( $number ) {
164 45
	return give_maybe_sanitize_amount( $number, 6 );
165 45
}
166 45
167 45
/**
168 45
 * Sanitize Amount before saving to database
169 45
 *
170 45
 * @since      1.8.12
171 45
 *
172 45
 * @param  int|float|string $number     Expects either a float or a string with a decimal separator only (no thousands)
173 45
 * @param  int|bool         $dp         Number of decimals
174 45
 * @param  bool             $trim_zeros From end of string
175 45
 *
176 45
 * @return string $amount Newly sanitized amount
177 45
 */
178 45
function give_maybe_sanitize_amount( $number, $dp = false, $trim_zeros = false ) {
179 45
	$thousand_separator = give_get_price_thousand_separator();
180 45
	$decimal_separator  = give_get_price_decimal_separator();
181 45
	$number_decimals    = is_bool( $dp ) ? give_get_price_decimals() : $dp;
182 45
183 45
	// Explode number by . decimal separator.
184 45
	$number_parts = explode( '.', $number );
185 45
186 45
	/*
187 45
	 * Bailout: Quick format number
188 45
	 */
189 45
	if ( empty( $number ) || ( ! is_numeric( $number ) && ! is_string( $number ) ) ) {
190 45
		return $number;
191 45
	}
192
193
	// Remove currency symbols from number if any.
194
	$number = trim( str_replace( give_currency_symbols( true ), '', $number ) );
195
196
	if (
197
		// Non formatted number.
198
		(
199 45
			( false === strpos( $number, $thousand_separator ) ) &&
200 45
			( false === strpos( $number, $decimal_separator ) )
201
		) ||
202
203
		// Decimal formatted number.
204
205
		// If number of decimal place set to non zero and
206
		// number only contains `.` as separator, precision set to less then or equal to number of decimal
207
		// then number will be consider as decimal formatted which means number is already sanitized.
208
		(
209
			$number_decimals &&
210
			'.' === $thousand_separator &&
211
			false !== strpos( $number, $thousand_separator ) &&
212
			false === strpos( $number, $decimal_separator ) &&
213
			2 === count( $number_parts ) &&
214
			( $number_decimals >= strlen( $number_parts[1] ) )
215
		)
216
	) {
217
		return number_format( $number, $number_decimals, '.', '' );
218
	}
219
220
	// Handle thousand separator as '.'
221
	// Handle sanitize database values.
222
	$is_db_sanitize_val = ( 2 === count( $number_parts ) &&
223
	                        is_numeric( $number_parts[0] ) &&
224
	                        is_numeric( $number_parts[1] ) &&
225
	                        ( 6 === strlen( $number_parts[1] ) ) );
226
227
	if ( $is_db_sanitize_val ) {
228
		// Sanitize database value.
229
		return number_format( $number, $number_decimals, '.', '' );
230
231
	} elseif (
232
		'.' === $thousand_separator &&
233
		false !== strpos( $number, $thousand_separator )
234
	) {
235
		// Fix point thousand separator value.
236
		$number = str_replace( '.', '', $number );
237
	}
238 45
239
	return give_sanitize_amount( $number, $number_decimals, $trim_zeros );
240
}
241
242
/**
243 45
 * Sanitize Amount
244
 *
245
 * Note: Use this give_maybe_sanitize_amount function instead for sanitizing number.
246
 *
247
 * Returns a sanitized amount by stripping out thousands separators.
248
 *
249
 * @since      1.0
250
 *
251
 * @param  int|float|string $number Expects either a float or a string with a decimal separator only (no thousands)
252
 * @param  int|bool         $dp Number of decimals
253
 * @param  bool             $trim_zeros From end of string
254
 *
255
 * @return string $amount Newly sanitized amount
256
 */
257 55
function give_sanitize_amount( $number, $dp = false, $trim_zeros = false ) {
258
259
	// Bailout.
260 55
	if ( empty( $number ) || ( ! is_numeric( $number ) && ! is_string( $number ) ) ) {
261 55
		return $number;
262 55
	}
263 55
264
	// Remove slash from amount.
265
	// If thousand or decimal separator is set to ' then in $_POST or $_GET param we will get an escaped number.
266
	// To prevent notices and warning remove slash from amount/number.
267
	$number = wp_unslash( $number );
268
269 55
	$thousand_separator = give_get_price_thousand_separator();
270
271
	$locale   = localeconv();
272
	$decimals = array( give_get_price_decimal_separator(), $locale['decimal_point'], $locale['mon_decimal_point'] );
273
274
	// Remove locale from string
275
	if ( ! is_float( $number ) ) {
276
		$number = str_replace( $decimals, '.', $number );
277
	}
278
279
	// Remove thousand amount formatting if amount has.
280
	// This condition use to add backward compatibility to version before 1.6, because before version 1.6 we were saving formatted amount to db.
281
	// Do not replace thousand separator from price if it is same as decimal separator, because it will be already replace by above code.
282
	if ( ! in_array( $thousand_separator, $decimals ) && ( false !== strpos( $number, $thousand_separator ) ) ) {
283
		$number = str_replace( $thousand_separator, '', $number );
284
	} elseif ( in_array( $thousand_separator, $decimals ) ) {
285
		$number = preg_replace( '/\.(?=.*\.)/', '', $number );
286
	}
287
288
	// Remove non numeric entity before decimal separator.
289
	$number     = preg_replace( '/[^0-9\.]/', '', $number );
290
	$default_dp = give_get_price_decimals();
291
292
	// Reset negative amount to zero.
293
	if ( 0 > $number ) {
294
		$number = number_format( 0, $default_dp, '.' );
295
	}
296
297
	// If number does not have decimal then add number of decimals to it.
298
	if (
299
		false === strpos( $number, '.' )
300
		|| ( $default_dp > strlen( substr( $number, strpos( $number, '.' ) + 1 ) ) )
301
	) {
302
		$number = number_format( $number, $default_dp, '.', '' );
303
	}
304
305
	// Format number by custom number of decimals.
306
	if ( false !== $dp ) {
307
		$dp     = intval( is_bool( $dp ) ? $default_dp : $dp );
308
		$dp     = apply_filters( 'give_sanitize_amount_decimals', $dp, $number );
309
		$number = number_format( floatval( $number ), $dp, '.', '' );
310
	}
311
312
	// Trim zeros.
313
	if ( $trim_zeros && strstr( $number, '.' ) ) {
314
		$number = rtrim( rtrim( $number, '0' ), '.' );
315
	}
316
317
	return apply_filters( 'give_sanitize_amount', $number );
318
}
319
320
/**
321
 * Returns a nicely formatted amount.
322
 *
323
 * @since 1.0
324
 *
325
 * @param string $amount      Price amount to format
326
 * @param array  $args        Array of arguments.
327
 *
328
 * @return string $amount   Newly formatted amount or Price Not Available
329
 */
330
function give_format_amount( $amount, $args = array() ) {
331
	// Backward compatibility.
332
	if( is_bool( $args ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
333
		$args = array( 'decimal' => $args );
334
	}
335
336
	$default_args = array(
337
		'decimal'     => true,
338
		'sanitize'    => true,
339
		'donation_id' => 0,
340
		'currency'    => '',
341
	);
342
343
	$args = wp_parse_args( $args, $default_args );
344
345
	// Set Currency based on donation id, if required.
346
	if( $args['donation_id'] && empty( $args['currency'] ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
347
		$donation_meta =  give_get_meta( $args['donation_id'], '_give_payment_meta', true );
0 ignored issues
show
introduced by
Expected 1 space after "="; 2 found
Loading history...
348
		$args['currency'] = $donation_meta['currency'];
349
	}
350
351
	$formatted     = 0;
352
	$currency      = ! empty( $args['currency'] ) ? $args['currency'] : give_get_currency( $args['donation_id'] );
353
	$thousands_sep = give_get_price_thousand_separator( $currency );
354
	$decimal_sep   = give_get_price_decimal_separator( $currency );
355
	$decimals      = ! empty( $args['decimal'] ) ? give_get_price_decimals( $currency ) : 0;
356
357
	if ( ! empty( $amount ) ) {
358
		// Sanitize amount before formatting.
359
		$amount = ! empty( $args['sanitize'] ) ?
360
			give_maybe_sanitize_amount( $amount, $decimals ) :
361
			number_format( $amount, $decimals, '.', '' );
362
363
		switch ( $currency ) {
364
			case 'INR':
365
				$decimal_amount = '';
366
367
				// Extract decimals from amount
368
				if ( ( $pos = strpos( $amount, '.' ) ) !== false ) {
0 ignored issues
show
introduced by
Found "!== false". Use Yoda Condition checks, you must
Loading history...
369
					if ( ! empty( $decimals ) ) {
370
						$decimal_amount = substr( round( substr( $amount, $pos ), $decimals ), 1 );
371
						$amount         = substr( $amount, 0, $pos );
372
373
						if ( ! $decimal_amount ) {
374
							$decimal_amount = substr( '.0000000000', 0, ( $decimals + 1 ) );
375
						} elseif ( ( $decimals + 1 ) > strlen( $decimal_amount ) ) {
376
							$decimal_amount = substr( "{$decimal_amount}000000000", 0, ( $decimals + 1 ) );
377
						}
0 ignored issues
show
introduced by
Blank line found after control structure
Loading history...
378
379
					} else {
380
						$amount = number_format( $amount, $decimals, $decimal_sep, '' );
381
					}
382
				}
383
384
				// Extract last 3 from amount
385
				$result = substr( $amount, - 3 );
386
				$amount = substr( $amount, 0, - 3 );
387
388
				// Apply digits 2 by 2
389
				while ( strlen( $amount ) > 0 ) {
390
					$result = substr( $amount, - 2 ) . $thousands_sep . $result;
391
					$amount = substr( $amount, 0, - 2 );
392
				}
393
394
				$formatted = $result . $decimal_amount;
395
				break;
396
397
			default:
398
				$formatted = number_format( $amount, $decimals, $decimal_sep, $thousands_sep );
399
		}
400
	}
401
402
	/**
403
	 * Filter the formatted amount
404
	 *
405
	 * @since 1.0
406
	 */
407
	return apply_filters( 'give_format_amount', $formatted, $amount, $decimals, $decimal_sep, $thousands_sep, $currency, $args );
408
}
409
410
411
/**
412
 * Get human readable amount.
413
 *
414
 * Note: This function only support large number formatting from million to trillion
415
 *
416
 * @since 1.6
417
 *
418
 * @use   give_get_price_thousand_separator Get thousand separator.
419
 *
420
 * @param string $amount formatted amount number.
421
 * @param array  $args   Array of arguments.
422
 *
423
 * @return float|string  formatted amount number with large number names.
424
 */
425
function give_human_format_large_amount( $amount, $args = array() ) {
426
	// Bailout.
427
	if( empty( $amount ) ) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
428
		return '';
429
	};
430
431
	// Set default currency;
432
	if( empty( $args['currency'] )) {
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
introduced by
No space before closing parenthesis is prohibited
Loading history...
433
		$args['currency'] = give_get_currency();
434
	}
435
436
	// Get thousand separator.
437
	$thousands_sep = give_get_price_thousand_separator();
438
439
	// Sanitize amount.
440
	$sanitize_amount = give_maybe_sanitize_amount( $amount );
441
442
	// Explode amount to calculate name of large numbers.
443
	$amount_array = explode( $thousands_sep, $amount );
444
445
	// Calculate amount parts count.
446
	$amount_count_parts = count( $amount_array );
447
448
	// Human format amount (default).
449
	$human_format_amount = $amount;
450
451
	switch ( $args['currency'] ) {
452 View Code Duplication
		case 'INR':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
453
			// Calculate large number formatted amount.
454
			if ( 4 < $amount_count_parts ) {
455
				$human_format_amount = sprintf( esc_html__( '%s arab', 'give' ), round( ( $sanitize_amount / 1000000000 ), 2 ) );
456
			} elseif ( 3 < $amount_count_parts ) {
457
				$human_format_amount = sprintf( esc_html__( '%s crore', 'give' ), round( ( $sanitize_amount / 10000000 ), 2 ) );
458
			} elseif ( 2 < $amount_count_parts ) {
459
				$human_format_amount = sprintf( esc_html__( '%s lakh', 'give' ), round( ( $sanitize_amount / 100000 ), 2 ) );
460
			}
461
			break;
462 View Code Duplication
		default:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
463
			// Calculate large number formatted amount.
464
			if ( 4 < $amount_count_parts ) {
465
				$human_format_amount = sprintf( esc_html__( '%s trillion', 'give' ), round( ( $sanitize_amount / 1000000000000 ), 2 ) );
466
			} elseif ( 3 < $amount_count_parts ) {
467
				$human_format_amount = sprintf( esc_html__( '%s billion', 'give' ), round( ( $sanitize_amount / 1000000000 ), 2 ) );
468
			} elseif ( 2 < $amount_count_parts ) {
469
				$human_format_amount = sprintf( esc_html__( '%s million', 'give' ), round( ( $sanitize_amount / 1000000 ), 2 ) );
470
			}
471
	}
472
473
	return apply_filters( 'give_human_format_large_amount', $human_format_amount, $amount, $sanitize_amount );
474
}
475
476
/**
477
 * Returns a nicely formatted amount with custom decimal separator.
478
 *
479
 * @since 1.0
480
 *
481
 * @param int|float|string $amount   Formatted or sanitized price
482
 * @param int|bool         $dp       number of decimals
483
 * @param bool             $sanitize Whether or not sanitize number
484
 *
485
 * @return string $amount Newly formatted amount or Price Not Available
486
 */
487
function give_format_decimal( $amount, $dp = false, $sanitize = true ) {
488
	$decimal_separator = give_get_price_decimal_separator();
489
	$formatted_amount  = $sanitize ?
490
		give_maybe_sanitize_amount( $amount, $dp ) :
491
		number_format( $amount, ( is_bool( $dp ) ? give_get_price_decimals() : $dp ), '.', '' );
492
493
	if ( false !== strpos( $formatted_amount, '.' ) ) {
494
		$formatted_amount = str_replace( '.', $decimal_separator, $formatted_amount );
495
	}
496
497
	return apply_filters( 'give_format_decimal', $formatted_amount, $amount, $decimal_separator );
498
}
499
500
/**
501
 * Formats the currency displayed.
502
 *
503
 * @since 1.0
504
 *
505
 * @param string $price The donation amount.
506
 * @param string $currency The currency code.
507
 * @param bool   $decode_currency Whether to decode the currency HTML format or not.
508
 *
509
 * @return mixed|string
510
 */
511
function give_currency_filter( $price = '', $currency = '', $decode_currency = false ) {
512
513
	if ( empty( $currency ) || ! array_key_exists( (string) $currency, give_get_currencies() ) ) {
514
		$currency = give_get_currency();
515
	}
516
517
	$position = give_get_option( 'currency_position', 'before' );
518
519
	$negative = $price < 0;
520
521
	if ( $negative ) {
522
		// Remove proceeding "-".
523
		$price = substr( $price, 1 );
524
	}
525
526
	$symbol = give_currency_symbol( $currency, $decode_currency );
527
528
	switch ( $currency ) :
529
		case 'GBP' :
530
		case 'BRL' :
531
		case 'EUR' :
532
		case 'USD' :
533
		case 'AUD' :
534
		case 'CAD' :
535
		case 'HKD' :
536
		case 'MXN' :
537
		case 'NZD' :
538
		case 'SGD' :
539
		case 'JPY' :
540
		case 'THB' :
541
		case 'INR' :
542
		case 'RIAL' :
543
		case 'TRY' :
544
		case 'RUB' :
545
		case 'SEK' :
546
		case 'PLN' :
547
		case 'PHP' :
548
		case 'TWD' :
549
		case 'MYR' :
550
		case 'CZK' :
551
		case 'DKK' :
552
		case 'HUF' :
553
		case 'ILS' :
554
		case 'MAD' :
555
		case 'KRW' :
556
		case 'ZAR' :
557
			$formatted = ( 'before' === $position ? $symbol . $price : $price . $symbol );
558
			break;
559 View Code Duplication
		case 'NOK' :
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
560
			$formatted = ( 'before' === $position ? $symbol . ' ' . $price : $price . ' ' . $symbol );
561
			break;
562 View Code Duplication
		default :
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
563
			$formatted = ( 'before' === $position ? $currency . ' ' . $price : $price . ' ' . $currency );
564
			break;
565
	endswitch;
566
567
	/**
568
	 * Filter formatted amount with currency
569
	 *
570
	 * Filter name depends upon current value of currency and currency position.
571
	 * For example :
572
	 *           if currency is USD and currency position is before then
573
	 *           filter name will be give_usd_currency_filter_before
574
	 *
575
	 *           and if currency is USD and currency position is after then
576
	 *           filter name will be give_usd_currency_filter_after
577
	 */
578
	$formatted = apply_filters( 'give_' . strtolower( $currency ) . "_currency_filter_{$position}", $formatted, $currency, $price );
579
580
	if ( $negative ) {
581
		// Prepend the minus sign before the currency sign.
582
		$formatted = '-' . $formatted;
583
	}
584
585
	return $formatted;
586
}
587
588
589
/**
590
 * Get date format string on basis of given context.
591
 *
592
 * @since 1.7
593
 *
594
 * @param  string $date_context Date format context name.
595
 *
596
 * @return string                  Date format string
597
 */
598
function give_date_format( $date_context = '' ) {
599
	/**
600
	 * Filter the date context
601
	 *
602
	 * You can add your own date context or use already exist context.
603
	 * For example:
604
	 *    add_filter( 'give_date_format_contexts', 'add_new_date_contexts' );
605
	 *    function add_new_date_contexts( $date_format_contexts ) {
606
	 *        // You can add single context like this $date_format_contexts['checkout'] = 'F j, Y';
607
	 *        // Instead add multiple date context at once.
608
	 *        $new_date_format_contexts = array(
609
	 *            'checkout' => 'F j, Y',
610
	 *            'report'   => 'Y-m-d',
611
	 *            'email'    => 'm/d/Y',
612
	 *        );
613
	 *
614
	 *       // Merge date contexts array only if you are adding multiple date contexts at once otherwise return  $date_format_contexts.
615
	 *       return array_merge( $new_date_format_contexts, $date_format_contexts );
616
	 *
617
	 *    }
618
	 */
619
	$date_format_contexts = apply_filters( 'give_date_format_contexts', array() );
620
621
	// Set date format to default date format.
622
	$date_format = get_option( 'date_format' );
623
624
	// Update date format if we have non empty date format context array and non empty date format string for that context.
625
	if ( $date_context && ! empty( $date_format_contexts ) && array_key_exists( $date_context, $date_format_contexts ) ) {
626
		$date_format = ! empty( $date_format_contexts[ $date_context ] )
627
			? $date_format_contexts[ $date_context ]
628
			: $date_format;
629
	}
630
631
	return apply_filters( 'give_date_format', $date_format );
632
}
633
634
/**
635
 * Get cache key.
636
 *
637
 * @since  1.7
638
 * @deprecated 1.8.7 You can access this function from Give_Cache.
639
 *
640
 * @param  string $action Cache key prefix.
641
 * @param array  $query_args Query array.
642
 *
643
 * @return string
644
 */
645
function give_get_cache_key( $action, $query_args ) {
646
	return Give_Cache::get_key( $action, $query_args );
647
}
648
649
/**
650
 * Clean variables using sanitize_text_field. Arrays are cleaned recursively.
651
 * Non-scalar values are ignored.
652
 *
653
 * @since  1.8
654
 *
655
 * @param  string|array $var
656
 *
657
 * @return string|array
658
 */
659
function give_clean( $var ) {
660
	if ( is_array( $var ) ) {
661
		return array_map( 'give_clean', $var );
662
	} else {
663
		return is_scalar( $var ) ? sanitize_text_field( $var ) : $var;
664
	}
665
}
666
667
/**
668
 * Transforms php.ini notation for numbers (like '2M') to an integer.
669
 *
670
 * @since 1.8
671
 *
672
 * @param $size
673
 *
674
 * @return int
675
 */
676
function give_let_to_num( $size ) {
677
	$l   = substr( $size, - 1 );
678
	$ret = substr( $size, 0, - 1 );
679
	switch ( strtoupper( $l ) ) {
680
		case 'P':
681
			$ret *= 1024;
682
		case 'T':
683
			$ret *= 1024;
684
		case 'G':
685
			$ret *= 1024;
686
		case 'M':
687
			$ret *= 1024;
688
		case 'K':
689
			$ret *= 1024;
690
	}
691
692
	return $ret;
693
}
694
695
/**
696
 * Verify nonce.
697
 *
698
 * @since 1.8
699
 *
700
 * @param        $nonce
701
 * @param int   $action
702
 * @param array $wp_die_args
703
 */
704
function give_validate_nonce( $nonce, $action = - 1, $wp_die_args = array() ) {
705
706
	$default_wp_die_args = array(
707
		'message' => esc_html__( 'Nonce verification has failed.', 'give' ),
708
		'title'   => esc_html__( 'Error', 'give' ),
709
		'args'    => array(
710
			'response' => 403,
711
		),
712
	);
713
714
	$wp_die_args = wp_parse_args( $wp_die_args, $default_wp_die_args );
715
716
	if ( ! wp_verify_nonce( $nonce, $action ) ) {
717
		wp_die(
718
			$wp_die_args['message'],
719
			$wp_die_args['title'],
720
			$wp_die_args['args']
721
		);
722
	}
723
}
724
725
/**
726
 * Check variable and get default or valid value.
727
 *
728
 * Helper function to check if a variable is set, empty, etc.
729
 *
730
 * @since 1.8
731
 *
732
 * @param                   $variable
733
 * @param string (optional) $conditional , default value: isset
734
 * @param bool (optional)   $default , default value: false
735
 *
736
 * @return mixed
737
 */
738
function give_check_variable( $variable, $conditional = '', $default = false ) {
739
740
	switch ( $conditional ) {
741
		case 'isset_empty':
742
			$variable = ( isset( $variable ) && ! empty( $variable ) ) ? $variable : $default;
743
			break;
744
745
		case 'empty':
746
			$variable = ! empty( $variable ) ? $variable : $default;
747
			break;
748
749
		case 'null':
750
			$variable = ! is_null( $variable ) ? $variable : $default;
751
			break;
752
753
		default:
754
			$variable = isset( $variable ) ? $variable : $default;
755
756
	}
757
758
	return $variable;
759
760
}
761