Completed
Push — develop ( dc7f10...49e2fc )
by Remco
02:19
created

Parser   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
dl 0
loc 55
rs 10
c 0
b 0
f 0
wmc 5
lcom 0
cbo 1

1 Method

Rating   Name   Duplication   Size   Complexity  
B parse() 0 44 5
1
<?php
2
/**
3
 * Parser
4
 *
5
 * @author    Pronamic <[email protected]>
6
 * @copyright 2005-2018 Pronamic
7
 * @license   GPL-3.0-or-later
8
 * @package   Pronamic\WordPress\Money
9
 */
10
11
namespace Pronamic\WordPress\Money;
12
13
/**
14
 * Parser
15
 *
16
 * @author  Remco Tolsma
17
 * @version 1.2.0
18
 * @since   1.1.0
19
 */
20
class Parser {
21
	/**
22
	 * Parse.
23
	 *
24
	 * @link https://github.com/wp-pay/core/blob/2.0.2/src/Core/Util.php#L128-L176
25
	 *
26
	 * @param string $string String to parse as money.
27
	 *
28
	 * @return Money
29
	 */
30
	public function parse( $string ) {
31
		global $wp_locale;
32
33
		$decimal_sep = $wp_locale->number_format['decimal_point'];
34
35
		// Seperators.
36
		$seperators = array( $decimal_sep, '.', ',' );
37
		$seperators = array_unique( array_filter( $seperators ) );
38
39
		// Check.
40
		foreach ( array( - 3, - 2 ) as $i ) {
41
			$test = substr( $string, $i, 1 );
42
43
			if ( in_array( $test, $seperators, true ) ) {
44
				$decimal_sep = $test;
45
46
				break;
47
			}
48
		}
49
50
		// Split.
51
		$position = false;
52
53
		if ( is_string( $decimal_sep ) ) {
54
			$position = strrpos( $string, $decimal_sep );
55
		}
56
57
		if ( false !== $position ) {
58
			$full = substr( $string, 0, $position );
59
			$half = substr( $string, $position + 1 );
60
61
			$full = filter_var( $full, FILTER_SANITIZE_NUMBER_INT );
62
			$half = filter_var( $half, FILTER_SANITIZE_NUMBER_INT );
63
64
			$string = $full . '.' . $half;
65
		} else {
66
			$string = filter_var( $string, FILTER_SANITIZE_NUMBER_INT );
67
		}
68
69
		// Filter.
70
		$value = filter_var( $string, FILTER_VALIDATE_FLOAT );
71
72
		return new Money( $value );
73
	}
74
}
75