Passed
Pull Request — master (#45)
by Kiran
04:26
created

wpinv-helper-functions.php ➔ wpinv_thousands_separator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * Contains functions related to Invoicing plugin.
4
 *
5
 * @since 1.0.0
6
 * @package Invoicing
7
 */
8
 
9
// MUST have WordPress.
10
if ( !defined( 'WPINC' ) ) {
11
    exit( 'Do NOT access this file directly: ' . basename( __FILE__ ) );
12
}
13
14
function wpinv_item_quantities_enabled() {
15
    $ret = wpinv_get_option( 'item_quantities', true );
16
    
17
    return (bool) apply_filters( 'wpinv_item_quantities_enabled', $ret );
18
}
19
20
function wpinv_get_ip() {
21
    $ip = '127.0.0.1';
22
23
    if ( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
24
        $ip = sanitize_text_field( $_SERVER['HTTP_CLIENT_IP'] );
25
    } elseif ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
26
        $ip = sanitize_text_field( $_SERVER['HTTP_X_FORWARDED_FOR'] );
27
    } elseif( !empty( $_SERVER['REMOTE_ADDR'] ) ) {
28
        $ip = sanitize_text_field( $_SERVER['REMOTE_ADDR'] );
29
    }
30
    
31
    return apply_filters( 'wpinv_get_ip', $ip );
32
}
33
34
function wpinv_get_user_agent() {
35
    if ( ! empty( $_SERVER['HTTP_USER_AGENT'] ) ) {
36
        $user_agent = sanitize_text_field( $_SERVER['HTTP_USER_AGENT'] );
37
    } else {
38
        $user_agent = '';
39
    }
40
    
41
    return apply_filters( 'wpinv_get_user_agent', $user_agent );
42
}
43
44
function wpinv_sanitize_amount( $amount ) {
45
    $is_negative   = false;
46
    $thousands_sep = wpinv_thousands_separator();
47
    $decimal_sep   = wpinv_decimal_separator();
48
    $decimals = wpinv_decimals();
49
50
    // Sanitize the amount
51
    if ( $decimal_sep == ',' && false !== ( $found = strpos( $amount, $decimal_sep ) ) ) {
52
        if ( ( $thousands_sep == '.' || $thousands_sep == ' ' ) && false !== ( $found = strpos( $amount, $thousands_sep ) ) ) {
53
            $amount = str_replace( $thousands_sep, '', $amount );
54 View Code Duplication
        } elseif( empty( $thousands_sep ) && false !== ( $found = strpos( $amount, '.' ) ) ) {
55
            $amount = str_replace( '.', '', $amount );
56
        }
57
58
        $amount = str_replace( $decimal_sep, '.', $amount );
59 View Code Duplication
    } elseif( $thousands_sep == ',' && false !== ( $found = strpos( $amount, $thousands_sep ) ) ) {
60
        $amount = str_replace( $thousands_sep, '', $amount );
61
    }
62
63
    if( $amount < 0 ) {
64
        $is_negative = true;
65
    }
66
67
    $amount   = preg_replace( '/[^0-9\.]/', '', $amount );
68
69
    $decimals = apply_filters( 'wpinv_sanitize_amount_decimals', $decimals, $amount );
70
    $amount   = number_format( (double) $amount, $decimals, '.', '' );
71
72
    if( $is_negative ) {
73
        $amount *= -1;
74
    }
75
76
    return apply_filters( 'wpinv_sanitize_amount', $amount );
77
}
78
79
function wpinv_round_amount( $amount ) {
80
    $decimals = wpinv_decimals();
81
    
82
    $amount = round( (double)$amount, wpinv_currency_decimal_filter( $decimals ) );
83
84
    return apply_filters( 'wpinv_round_amount', $amount );
85
}
86
87
function wpinv_get_invoice_statuses( $trashed = false ) {
88
    $invoice_statuses = array(
89
        'pending'       => __( 'Pending Payment', 'invoicing' ),
90
        'publish'       => __( 'Paid', 'invoicing' ),
91
        'wpi-processing'    => __( 'Processing', 'invoicing' ),
92
        'wpi-onhold'        => __( 'On Hold', 'invoicing' ),
93
        'wpi-refunded'      => __( 'Refunded', 'invoicing' ),
94
        'wpi-cancelled'     => __( 'Cancelled', 'invoicing' ),
95
        'wpi-failed'        => __( 'Failed', 'invoicing' ),
96
        'wpi-renewal'       => __( 'Renewal Payment', 'invoicing' )
97
    );
98
    
99
    if ( $trashed ) {
100
        $invoice_statuses['trash'] = __( 'Trash', 'invoicing' );
101
    }
102
103
    return apply_filters( 'wpinv_statuses', $invoice_statuses );
104
}
105
106
function wpinv_status_nicename( $status ) {
107
    $statuses = wpinv_get_invoice_statuses();
108
    $status   = isset( $statuses[$status] ) ? $statuses[$status] : __( $status, 'invoicing' );
109
110
    return $status;
111
}
112
113
function wpinv_get_currency() {
114
    $currency = wpinv_get_option( 'currency', 'USD' );
0 ignored issues
show
Documentation introduced by
'USD' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
115
    
116
    return apply_filters( 'wpinv_currency', $currency );
117
}
118
119
function wpinv_currency_symbol( $currency = '' ) {
120
    if ( empty( $currency ) ) {
121
        $currency = wpinv_get_currency();
122
    }
123
    
124
    $symbols = apply_filters( 'wpinv_currency_symbols', array(
125
        'AED' => 'د.إ',
126
        'ARS' => '&#36;',
127
        'AUD' => '&#36;',
128
        'BDT' => '&#2547;&nbsp;',
129
        'BGN' => '&#1083;&#1074;.',
130
        'BRL' => '&#82;&#36;',
131
        'CAD' => '&#36;',
132
        'CHF' => '&#67;&#72;&#70;',
133
        'CLP' => '&#36;',
134
        'CNY' => '&yen;',
135
        'COP' => '&#36;',
136
        'CZK' => '&#75;&#269;',
137
        'DKK' => 'DKK',
138
        'DOP' => 'RD&#36;',
139
        'EGP' => 'EGP',
140
        'EUR' => '&euro;',
141
        'GBP' => '&pound;',
142
        'HKD' => '&#36;',
143
        'HRK' => 'Kn',
144
        'HUF' => '&#70;&#116;',
145
        'IDR' => 'Rp',
146
        'ILS' => '&#8362;',
147
        'INR' => '&#8377;',
148
        'ISK' => 'Kr.',
149
        'JPY' => '&yen;',
150
        'KES' => 'KSh',
151
        'KRW' => '&#8361;',
152
        'LAK' => '&#8365;',
153
        'MXN' => '&#36;',
154
        'MYR' => '&#82;&#77;',
155
        'NGN' => '&#8358;',
156
        'NOK' => '&#107;&#114;',
157
        'NPR' => '&#8360;',
158
        'NZD' => '&#36;',
159
        'PHP' => '&#8369;',
160
        'PKR' => '&#8360;',
161
        'PLN' => '&#122;&#322;',
162
        'PYG' => '&#8370;',
163
        'RMB' => '&yen;',
164
        'RON' => 'lei',
165
        'RUB' => '&#8381;',
166
        'SAR' => '&#x631;.&#x633;',
167
        'SEK' => '&#107;&#114;',
168
        'SGD' => '&#36;',
169
        'THB' => '&#3647;',
170
        'TRY' => '&#8378;',
171
        'TWD' => '&#78;&#84;&#36;',
172
        'UAH' => '&#8372;',
173
        'USD' => '&#36;',
174
        'VND' => '&#8363;',
175
        'ZAR' => '&#82;',
176
    ) );
177
178
    $currency_symbol = isset( $symbols[$currency] ) ? $symbols[$currency] : '&#36;';
179
180
    return apply_filters( 'wpinv_currency_symbol', $currency_symbol, $currency );
181
}
182
183
function wpinv_currency_position() {
184
    $position = wpinv_get_option( 'currency_position', 'left' );
0 ignored issues
show
Documentation introduced by
'left' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
185
    
186
    return apply_filters( 'wpinv_currency_position', $position );
187
}
188
189
function wpinv_thousands_separator() {
190
    $thousand_sep = wpinv_get_option( 'thousands_separator', ',' );
0 ignored issues
show
Documentation introduced by
',' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
191
    
192
    return apply_filters( 'wpinv_thousands_separator', $thousand_sep );
193
}
194
195
function wpinv_decimal_separator() {
196
    $decimal_sep = wpinv_get_option( 'decimal_separator', '.' );
0 ignored issues
show
Documentation introduced by
'.' is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
197
    
198
    return apply_filters( 'wpinv_decimal_separator', $decimal_sep );
199
}
200
201
function wpinv_decimals() {
202
    $decimals = apply_filters( 'wpinv_decimals', wpinv_get_option( 'decimals', 2 ) );
0 ignored issues
show
Documentation introduced by
2 is of type integer, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
203
    
204
    return absint( $decimals );
205
}
206
207
function wpinv_get_currencies() {
208
    $currencies = array(
209
        'USD'  => __( 'US Dollars (&#36;)', 'invoicing' ),
210
        'EUR'  => __( 'Euros (&euro;)', 'invoicing' ),
211
        'GBP'  => __( 'Pounds Sterling (&pound;)', 'invoicing' ),
212
        'AUD'  => __( 'Australian Dollars (&#36;)', 'invoicing' ),
213
        'BRL'  => __( 'Brazilian Real (R&#36;)', 'invoicing' ),
214
        'CAD'  => __( 'Canadian Dollars (&#36;)', 'invoicing' ),
215
        'CLP'  => __( 'Chilean Peso (&#36;)', 'invoicing' ),
216
        'CNY'  => __( 'Chinese Yuan (&yen;)', 'invoicing' ),
217
        'CZK'  => __( 'Czech Koruna (&#75;&#269;)', 'invoicing' ),
218
        'DKK'  => __( 'Danish Krone (DKK)', 'invoicing' ),
219
        'HKD'  => __( 'Hong Kong Dollar (&#36;)', 'invoicing' ),
220
        'HUF'  => __( 'Hungarian Forint (&#70;&#116;)', 'invoicing' ),
221
        'INR'  => __( 'Indian Rupee (&#8377;)', 'invoicing' ),
222
        'ILS'  => __( 'Israeli Shekel (&#8362;)', 'invoicing' ),
223
        'JPY'  => __( 'Japanese Yen (&yen;)', 'invoicing' ),
224
        'MYR'  => __( 'Malaysian Ringgit (&#82;&#77;)', 'invoicing' ),
225
        'MXN'  => __( 'Mexican Peso (&#36;)', 'invoicing' ),
226
        'NZD'  => __( 'New Zealand Dollar (&#36;)', 'invoicing' ),
227
        'NOK'  => __( 'Norwegian Krone (&#107;&#114;)', 'invoicing' ),
228
        'PHP'  => __( 'Philippine Peso (&#8369;)', 'invoicing' ),
229
        'PLN'  => __( 'Polish Zloty (&#122;&#322;)', 'invoicing' ),
230
        'SGD'  => __( 'Singapore Dollar (&#36;)', 'invoicing' ),
231
        'SEK'  => __( 'Swedish Krona (&#107;&#114;)', 'invoicing' ),
232
        'CHF'  => __( 'Swiss Franc (&#67;&#72;&#70;)', 'invoicing' ),
233
        'TWD'  => __( 'Taiwan New Dollar (&#78;&#84;&#36;)', 'invoicing' ),
234
        'THB'  => __( 'Thai Baht (&#3647;)', 'invoicing' ),
235
        'TRY'  => __( 'Turkish Lira (&#8378;)', 'invoicing' ),
236
        'RIAL' => __( 'Iranian Rial (&#65020;)', 'invoicing' ),
237
        'RUB'  => __( 'Russian Ruble (&#8381;)', 'invoicing' ),
238
        'ZAR'  => __( 'South African Rand (&#82;)', 'invoicing' )
239
    );
240
    
241
    asort( $currencies );
242
243
    return apply_filters( 'wpinv_currencies', $currencies );
244
}
245
246
function wpinv_price( $amount = '', $currency = '' ) {
247
    if( empty( $currency ) ) {
248
        $currency = wpinv_get_currency();
249
    }
250
251
    $position = wpinv_currency_position();
252
253
    $negative = $amount < 0;
254
255
    if ( $negative ) {
256
        $amount = substr( $amount, 1 );
257
    }
258
259
    $symbol = wpinv_currency_symbol( $currency );
260
261
    if ( $position == 'left' || $position == 'left_space' ) {
262 View Code Duplication
        switch ( $currency ) {
263
            case "GBP" :
264
            case "BRL" :
265
            case "EUR" :
266
            case "USD" :
267
            case "AUD" :
268
            case "CAD" :
269
            case "HKD" :
270
            case "MXN" :
271
            case "NZD" :
272
            case "SGD" :
273
            case "JPY" :
274
                $price = $position == 'left_space' ? $symbol . ' ' .  $amount : $symbol . $amount;
275
                break;
276
            default :
277
                //$price = $currency . ' ' . $amount;
0 ignored issues
show
Unused Code Comprehensibility introduced by
36% 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...
278
                $price = $position == 'left_space' ? $symbol . ' ' .  $amount : $symbol . $amount;
279
                break;
280
        }
281
    } else {
282 View Code Duplication
        switch ( $currency ) {
283
            case "GBP" :
284
            case "BRL" :
285
            case "EUR" :
286
            case "USD" :
287
            case "AUD" :
288
            case "CAD" :
289
            case "HKD" :
290
            case "MXN" :
291
            case "SGD" :
292
            case "JPY" :
293
                $price = $position == 'right_space' ? $amount . ' ' .  $symbol : $amount . $symbol;
294
                break;
295
            default :
296
                //$price = $amount . ' ' . $currency;
0 ignored issues
show
Unused Code Comprehensibility introduced by
36% 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...
297
                $price = $position == 'right_space' ? $amount . ' ' .  $symbol : $amount . $symbol;
298
                break;
299
        }
300
    }
301
    
302
    if ( $negative ) {
303
        $price = '-' . $price;
304
    }
305
    
306
    $price = apply_filters( 'wpinv_' . strtolower( $currency ) . '_currency_filter_' . $position, $price, $currency, $amount );
307
308
    return $price;
309
}
310
311
function wpinv_format_amount( $amount, $decimals = NULL, $calculate = false ) {
312
    $thousands_sep = wpinv_thousands_separator();
313
    $decimal_sep   = wpinv_decimal_separator();
314
315
    if ( $decimals === NULL ) {
316
        $decimals = wpinv_decimals();
317
    }
318
319
    if ( $decimal_sep == ',' && false !== ( $sep_found = strpos( $amount, $decimal_sep ) ) ) {
320
        $whole = substr( $amount, 0, $sep_found );
321
        $part = substr( $amount, $sep_found + 1, ( strlen( $amount ) - 1 ) );
322
        $amount = $whole . '.' . $part;
323
    }
324
325 View Code Duplication
    if ( $thousands_sep == ',' && false !== ( $found = strpos( $amount, $thousands_sep ) ) ) {
326
        $amount = str_replace( ',', '', $amount );
327
    }
328
329 View Code Duplication
    if ( $thousands_sep == ' ' && false !== ( $found = strpos( $amount, $thousands_sep ) ) ) {
330
        $amount = str_replace( ' ', '', $amount );
331
    }
332
333
    if ( empty( $amount ) ) {
334
        $amount = 0;
335
    }
336
    
337
    $decimals  = apply_filters( 'wpinv_amount_format_decimals', $decimals ? $decimals : 0, $amount, $calculate );
338
    $formatted = number_format( (float)$amount, $decimals, $decimal_sep, $thousands_sep );
339
    
340
    if ( $calculate ) {
341
        if ( $thousands_sep === "," ) {
342
            $formatted = str_replace( ",", "", $formatted );
343
        }
344
        
345
        if ( $decimal_sep === "," ) {
346
            $formatted = str_replace( ",", ".", $formatted );
347
        }
348
    }
349
350
    return apply_filters( 'wpinv_amount_format', $formatted, $amount, $decimals, $decimal_sep, $thousands_sep, $calculate );
351
}
352
353
function wpinv_sanitize_key( $key ) {
354
    $raw_key = $key;
355
    $key = preg_replace( '/[^a-zA-Z0-9_\-\.\:\/]/', '', $key );
356
357
    return apply_filters( 'wpinv_sanitize_key', $key, $raw_key );
358
}
359
360
function wpinv_get_file_extension( $str ) {
361
    $parts = explode( '.', $str );
362
    return end( $parts );
363
}
364
365
function wpinv_string_is_image_url( $str ) {
366
    $ext = wpinv_get_file_extension( $str );
367
368
    switch ( strtolower( $ext ) ) {
369
        case 'jpeg';
370
        case 'jpg';
371
            $return = true;
372
            break;
373
        case 'png';
374
            $return = true;
375
            break;
376
        case 'gif';
377
            $return = true;
378
            break;
379
        default:
380
            $return = false;
381
            break;
382
    }
383
384
    return (bool)apply_filters( 'wpinv_string_is_image', $return, $str );
385
}
386
387
function wpinv_error_log( $log, $title = '', $file = '', $line = '', $exit = false ) {
388
    $should_log = apply_filters( 'wpinv_log_errors', WP_DEBUG );
389
    
390
    if ( true === $should_log ) {
391
        $label = '';
392
        if ( $file && $file !== '' ) {
393
            $label .= basename( $file ) . ( $line ? '(' . $line . ')' : '' );
394
        }
395
        
396
        if ( $title && $title !== '' ) {
397
            $label = $label !== '' ? $label . ' ' : '';
398
            $label .= $title . ' ';
399
        }
400
        
401
        $label = $label !== '' ? trim( $label ) . ' : ' : '';
402
        
403
        if ( is_array( $log ) || is_object( $log ) ) {
404
            error_log( $label . print_r( $log, true ) );
405
        } else {
406
            error_log( $label . $log );
407
        }
408
        
409
        if ( $exit ) {
410
            exit;
411
        }
412
    }
413
}
414
415
function wpinv_is_ajax_disabled() {
416
    $retval = false;
417
    return apply_filters( 'wpinv_is_ajax_disabled', $retval );
418
}
419
420
function wpinv_get_current_page_url( $nocache = false ) {
421
    global $wp;
422
423
    if ( get_option( 'permalink_structure' ) ) {
424
        $base = trailingslashit( home_url( $wp->request ) );
425
    } else {
426
        $base = add_query_arg( $wp->query_string, '', trailingslashit( home_url( $wp->request ) ) );
427
        $base = remove_query_arg( array( 'post_type', 'name' ), $base );
428
    }
429
430
    $scheme = is_ssl() ? 'https' : 'http';
431
    $uri    = set_url_scheme( $base, $scheme );
432
433
    if ( is_front_page() ) {
434
        $uri = home_url( '/' );
435
    } elseif ( wpinv_is_checkout( array(), false ) ) {
0 ignored issues
show
Unused Code introduced by
The call to wpinv_is_checkout() has too many arguments starting with array().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
436
        $uri = wpinv_get_checkout_uri();
437
    }
438
439
    $uri = apply_filters( 'wpinv_get_current_page_url', $uri );
440
441
    if ( $nocache ) {
442
        $uri = wpinv_add_cache_busting( $uri );
443
    }
444
445
    return $uri;
446
}
447
448
function wpinv_get_php_arg_separator_output() {
449
	return ini_get( 'arg_separator.output' );
450
}
451
452
function wpinv_rgb_from_hex( $color ) {
453
    $color = str_replace( '#', '', $color );
454
    // Convert shorthand colors to full format, e.g. "FFF" -> "FFFFFF"
455
    $color = preg_replace( '~^(.)(.)(.)$~', '$1$1$2$2$3$3', $color );
456
457
    $rgb      = array();
458
    $rgb['R'] = hexdec( $color{0}.$color{1} );
459
    $rgb['G'] = hexdec( $color{2}.$color{3} );
460
    $rgb['B'] = hexdec( $color{4}.$color{5} );
461
462
    return $rgb;
463
}
464
465 View Code Duplication
function wpinv_hex_darker( $color, $factor = 30 ) {
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...
466
    $base  = wpinv_rgb_from_hex( $color );
467
    $color = '#';
468
469
    foreach ( $base as $k => $v ) {
470
        $amount      = $v / 100;
471
        $amount      = round( $amount * $factor );
472
        $new_decimal = $v - $amount;
473
474
        $new_hex_component = dechex( $new_decimal );
475
        if ( strlen( $new_hex_component ) < 2 ) {
476
            $new_hex_component = "0" . $new_hex_component;
477
        }
478
        $color .= $new_hex_component;
479
    }
480
481
    return $color;
482
}
483
484 View Code Duplication
function wpinv_hex_lighter( $color, $factor = 30 ) {
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...
485
    $base  = wpinv_rgb_from_hex( $color );
486
    $color = '#';
487
488
    foreach ( $base as $k => $v ) {
489
        $amount      = 255 - $v;
490
        $amount      = $amount / 100;
491
        $amount      = round( $amount * $factor );
492
        $new_decimal = $v + $amount;
493
494
        $new_hex_component = dechex( $new_decimal );
495
        if ( strlen( $new_hex_component ) < 2 ) {
496
            $new_hex_component = "0" . $new_hex_component;
497
        }
498
        $color .= $new_hex_component;
499
    }
500
501
    return $color;
502
}
503
504
function wpinv_light_or_dark( $color, $dark = '#000000', $light = '#FFFFFF' ) {
505
    $hex = str_replace( '#', '', $color );
506
507
    $c_r = hexdec( substr( $hex, 0, 2 ) );
508
    $c_g = hexdec( substr( $hex, 2, 2 ) );
509
    $c_b = hexdec( substr( $hex, 4, 2 ) );
510
511
    $brightness = ( ( $c_r * 299 ) + ( $c_g * 587 ) + ( $c_b * 114 ) ) / 1000;
512
513
    return $brightness > 155 ? $dark : $light;
514
}
515
516
function wpinv_format_hex( $hex ) {
517
    $hex = trim( str_replace( '#', '', $hex ) );
518
519
    if ( strlen( $hex ) == 3 ) {
520
        $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
521
    }
522
523
    return $hex ? '#' . $hex : null;
524
}
525
526
/**
527
 * Get truncated string with specified width.
528
 *
529
 * @since 1.0.0
530
 *
531
 * @param string $str The string being decoded.
532
 * @param int $start The start position offset. Number of characters from the beginning of string.
533
 *                      For negative value, number of characters from the end of the string.
534
 * @param int $width The width of the desired trim. Negative widths count from the end of the string.
535
 * @param string $trimmaker A string that is added to the end of string when string is truncated. Ex: "...".
536
 * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
537
 * @return string
538
 */
539
function wpinv_utf8_strimwidth( $str, $start, $width, $trimmaker = '', $encoding = 'UTF-8' ) {
540
    if ( function_exists( 'mb_strimwidth' ) ) {
541
        return mb_strimwidth( $str, $start, $width, $trimmaker, $encoding );
542
    }
543
    
544
    return wpinv_utf8_substr( $str, $start, $width, $encoding ) . $trimmaker;
545
}
546
547
/**
548
 * Get the string length.
549
 *
550
 * @since 1.0.0
551
 *
552
 * @param string $str The string being checked for length. 
553
 * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
554
 * @return int Returns the number of characters in string.
555
 */
556
function wpinv_utf8_strlen( $str, $encoding = 'UTF-8' ) {
557
    if ( function_exists( 'mb_strlen' ) ) {
558
        return mb_strlen( $str, $encoding );
559
    }
560
        
561
    return strlen( $str );
562
}
563
564
function wpinv_utf8_strtolower( $str, $encoding = 'UTF-8' ) {
565
    if ( function_exists( 'mb_strtolower' ) ) {
566
        return mb_strtolower( $str, $encoding );
567
    }
568
    
569
    return strtolower( $str );
570
}
571
572
function wpinv_utf8_strtoupper( $str, $encoding = 'UTF-8' ) {
573
    if ( function_exists( 'mb_strtoupper' ) ) {
574
        return mb_strtoupper( $str, $encoding );
575
    }
576
    
577
    return strtoupper( $str );
578
}
579
580
/**
581
 * Find position of first occurrence of string in a string
582
 *
583
 * @since 1.0.0
584
 *
585
 * @param string $str The string being checked.
586
 * @param string $find The string to find in input string.
587
 * @param int $offset The search offset. Default "0". A negative offset counts from the end of the string.
588
 * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
589
 * @return int Returns the position of the first occurrence of search in the string.
590
 */
591
function wpinv_utf8_strpos( $str, $find, $offset = 0, $encoding = 'UTF-8' ) {
592
    if ( function_exists( 'mb_strpos' ) ) {
593
        return mb_strpos( $str, $find, $offset, $encoding );
594
    }
595
        
596
    return strpos( $str, $find, $offset );
597
}
598
599
/**
600
 * Find position of last occurrence of a string in a string.
601
 *
602
 * @since 1.0.0
603
 *
604
 * @param string $str The string being checked, for the last occurrence of search.
605
 * @param string $find The string to find in input string.
606
 * @param int $offset Specifies begin searching an arbitrary number of characters into the string.
607
 * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
608
 * @return int Returns the position of the last occurrence of search.
609
 */
610
function wpinv_utf8_strrpos( $str, $find, $offset = 0, $encoding = 'UTF-8' ) {
611
    if ( function_exists( 'mb_strrpos' ) ) {
612
        return mb_strrpos( $str, $find, $offset, $encoding );
613
    }
614
        
615
    return strrpos( $str, $find, $offset );
616
}
617
618
/**
619
 * Get the part of string.
620
 *
621
 * @since 1.0.0
622
 *
623
 * @param string $str The string to extract the substring from.
624
 * @param int $start If start is non-negative, the returned string will start at the entered position in string, counting from zero.
625
 *                      If start is negative, the returned string will start at the entered position from the end of string. 
626
 * @param int|null $length Maximum number of characters to use from string.
627
 * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
628
 * @return string
629
 */
630
function wpinv_utf8_substr( $str, $start, $length = null, $encoding = 'UTF-8' ) {
631
    if ( function_exists( 'mb_substr' ) ) {
632
        if ( $length === null ) {
633
            return mb_substr( $str, $start, wpinv_utf8_strlen( $str, $encoding ), $encoding );
634
        } else {
635
            return mb_substr( $str, $start, $length, $encoding );
636
        }
637
    }
638
        
639
    return substr( $str, $start, $length );
640
}
641
642
/**
643
 * Get the width of string.
644
 *
645
 * @since 1.0.0
646
 *
647
 * @param string $str The string being decoded.
648
 * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
649
 * @return string The width of string.
650
 */
651
function wpinv_utf8_strwidth( $str, $encoding = 'UTF-8' ) {
652
    if ( function_exists( 'mb_strwidth' ) ) {
653
        return mb_strwidth( $str, $encoding );
654
    }
655
    
656
    return wpinv_utf8_strlen( $str, $encoding );
657
}
658
659
function wpinv_utf8_ucfirst( $str, $lower_str_end = false, $encoding = 'UTF-8' ) {
660
    if ( function_exists( 'mb_strlen' ) ) {
661
        $first_letter = wpinv_utf8_strtoupper( wpinv_utf8_substr( $str, 0, 1, $encoding ), $encoding );
662
        $str_end = "";
0 ignored issues
show
Unused Code introduced by
$str_end is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
663
        
664
        if ( $lower_str_end ) {
665
            $str_end = wpinv_utf8_strtolower( wpinv_utf8_substr( $str, 1, wpinv_utf8_strlen( $str, $encoding ), $encoding ), $encoding );
666
        } else {
667
            $str_end = wpinv_utf8_substr( $str, 1, wpinv_utf8_strlen( $str, $encoding ), $encoding );
668
        }
669
670
        return $first_letter . $str_end;
671
    }
672
    
673
    return ucfirst( $str );
674
}
675
676
function wpinv_utf8_ucwords( $str, $encoding = 'UTF-8' ) {
677
    if ( function_exists( 'mb_convert_case' ) ) {
678
        return mb_convert_case( $str, MB_CASE_TITLE, $encoding );
679
    }
680
    
681
    return ucwords( $str );
682
}
683
684
function wpinv_period_in_days( $period, $unit ) {
685
    $period = absint( $period );
686
    
687
    if ( $period > 0 ) {
688
        if ( in_array( strtolower( $unit ), array( 'w', 'week', 'weeks' ) ) ) {
689
            $period = $period * 7;
690
        } else if ( in_array( strtolower( $unit ), array( 'm', 'month', 'months' ) ) ) {
691
            $period = $period * 30;
692
        } else if ( in_array( strtolower( $unit ), array( 'y', 'year', 'years' ) ) ) {
693
            $period = $period * 365;
694
        }
695
    }
696
    
697
    return $period;
698
}
699