Completed
Branch FET-3467-waitlists (24004d)
by
unknown
86:26 queued 75:18
created

EEH_Money::get_currency_config()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 14
Code Lines 9

Duplication

Lines 3
Ratio 21.43 %

Importance

Changes 0
Metric Value
cc 4
eloc 9
nc 6
nop 1
dl 3
loc 14
rs 9.2
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file contains a helper class for money type actions.
4
 *
5
 * @since %VER%
6
 * @package  Event Espresso
7
 * @subpackage helper
8
 */
9
if ( ! defined('EVENT_ESPRESSO_VERSION')) exit('No direct script access allowed');
10
 /**
11
 *
12
 * Money helper class.
13
 * This class has helper methods that help with money related conversions and calculations.
14
 *
15
 * @since %VER%
16
 *
17
 * @package		Event Espresso
18
 * @subpackage	helpers
19
 * @author		Darren Ethier
20
 *
21
 * ------------------------------------------------------------------------
22
 */
23
class EEH_Money extends EEH_Base  {
24
25
26
    /**
27
     * This removes all localized money formatting from the incoming value
28
     *
29
     * @param int|float|string $money_value
30
     * @param string           $CNT_ISO
31
     * @return float
32
     * @throws EE_Error
33
     */
34
	public static function strip_localized_money_formatting($money_value, $CNT_ISO = '') {
35
        $currency_config = EEH_Money::get_currency_config($CNT_ISO);
36
        $money_value = str_replace(
37
		    array(
38
                $currency_config->thsnds,
39
                $currency_config->dec_mrk,
40
            ),
41
            array(
42
                '', // remove thousands separator
43
                '.', // convert decimal mark to what PHP expects
44
            ),
45
            $money_value
46
        );
47
        $money_value = filter_var(
48
            $money_value,
49
            FILTER_SANITIZE_NUMBER_FLOAT,
50
            FILTER_FLAG_ALLOW_FRACTION
51
        );
52
        return $money_value;
53
    }
54
55
56
57
    /**
58
     * This converts an incoming localized money value into a standard float item (to three decimal places)
59
     *
60
     * @param int|string $money_value
61
     * @return float
62
     * @throws EE_Error
63
     */
64
	public static function convert_to_float_from_localized_money($money_value ) {
65
		//float it! and round to three decimal places
66
        return round ( (float) EEH_Money::strip_localized_money_formatting($money_value), 3 );
67
	}
68
69
70
71
	/**
72
	 * For comparing floats. Default operator is '=', but see the $operator below for all options.
73
	 * This should be used to compare floats instead of normal '==' because floats
74
	 * are inherently imprecise, and so you can sometimes have two floats that appear to be identical
75
	 * but actually differ by 0.00000001.
76
	 *
77
	 * @see http://biostall.com/php-function-to-compare-floating-point-numbers
78
	 * @param float  $float1
79
	 * @param float  $float2
80
	 * @param string $operator  The operator. Valid options are =, <=, <, >=, >, <>, eq, lt, lte, gt, gte, ne
81
	 * @return bool whether the equation is true or false
82
	 * @throws EE_Error
83
	 */
84
85
	public static function compare_floats( $float1, $float2, $operator='=' ) {
86
		// Check numbers to 5 digits of precision
87
		$epsilon = 0.00001;
88
89
		$float1 = (float)$float1;
90
		$float2 = (float)$float2;
91
92
		switch ($operator) {
93
			// equal
94
			case "=":
95
			case "==":
96
			case "===":
97
			case "eq":
98
				if (abs($float1 - $float2) < $epsilon) {
99
					return true;
100
				}
101
				break;
102
			// less than
103
			case "<":
104 View Code Duplication
			case "lt":
105
				if (abs($float1 - $float2) < $epsilon) {
106
					return false;
107
				} else {
108
					if ($float1 < $float2) {
109
						return true;
110
					}
111
				}
112
				break;
113
			// less than or equal
114
			case "<=":
115 View Code Duplication
			case "lte":
116
				if (self::compare_floats($float1, $float2, '<') || self::compare_floats($float1, $float2, '=')) {
117
					return true;
118
				}
119
				break;
120
			// greater than
121
			case ">":
122 View Code Duplication
			case "gt":
123
				if (abs($float1 - $float2) < $epsilon) {
124
					return false;
125
				} else {
126
					if ($float1 > $float2) {
127
						return true;
128
					}
129
				}
130
				break;
131
			// greater than or equal
132
			case ">=":
133 View Code Duplication
			case "gte":
134
				if (self::compare_floats($float1, $float2, '>') || self::compare_floats($float1, $float2, '=')) {
135
					return true;
136
				}
137
				break;
138
			case "<>":
139
			case "!=":
140
			case "ne":
141
				if (abs($float1 - $float2) > $epsilon) {
142
					return true;
143
				}
144
				break;
145
			default:
146
				throw new EE_Error(__( "Unknown operator '" . $operator . "' in EEH_Money::compare_floats()", 'event_espresso' ) );
147
		}
148
149
		return false;
150
	}
151
152
153
154
    /**
155
     * This returns a localized format string suitable for jQplot.
156
     *
157
     * @param string $CNT_ISO  If this is provided, then will attempt to get the currency settings for the country.
158
     *                         Otherwise will use currency settings for current active country on site.
159
     * @return string
160
     * @throws EE_Error
161
     */
162
	public static function get_format_for_jqplot( $CNT_ISO = '') {
163
		//default format
164
		$format = 'f';
165
		$currency_config = $currency_config = EEH_Money::get_currency_config($CNT_ISO);
166
        //first get the decimal place and number of places
167
		$format = "%'." . $currency_config->dec_plc . $format;
168
		//currency symbol on right side.
169
		$format = $currency_config->sign_b4 ? $currency_config->sign . $format : $format . $currency_config->sign;
170
		return $format;
171
	}
172
173
174
175
    /**
176
     * This returns a localized format string suitable for usage with the Google Charts API format param.
177
     *
178
     * @param string $CNT_ISO  If this is provided, then will attempt to get the currency settings for the country.
179
     *                         Otherwise will use currency settings for current active country on site.
180
     *                         Note: GoogleCharts uses ICU pattern set
181
     *                         (@see http://icu-project.org/apiref/icu4c/classDecimalFormat.html#_details)
182
     * @return string
183
     * @throws EE_Error
184
     */
185
	public static function get_format_for_google_charts( $CNT_ISO = '' ) {
186
		$currency_config = EEH_Money::get_currency_config($CNT_ISO);
187
		$decimal_places_placeholder = str_pad( '', $currency_config->dec_plc, '0' );
188
		//first get the decimal place and number of places
189
		$format = '#,##0.' . $decimal_places_placeholder;
190
191
		//currency symbol on right side.
192
		$format = $currency_config->sign_b4 ? $currency_config->sign . $format : $format . $currency_config->sign;
193
		$formatterObject = array(
194
			'decimalSymbol' => $currency_config->dec_mrk,
195
			'groupingSymbol' => $currency_config->thsnds,
196
			'fractionDigits' => $currency_config->dec_plc,
197
		);
198
		if ( $currency_config->sign_b4 ) {
199
			$formatterObject['prefix'] = $currency_config->sign;
200
		} else {
201
			$formatterObject['suffix'] = $currency_config->sign;
202
		}
203
		return array(
204
			'format' => $format,
205
			'formatterObject' => $formatterObject,
206
		);
207
	}
208
209
210
211
    /**
212
     * @param string $CNT_ISO
213
     * @return EE_Currency_Config|null
214
     * @throws EE_Error
215
     */
216
    public static function get_currency_config($CNT_ISO = '')
217
    {
218
        //if CNT_ISO passed lets try to get currency settings for it.
219
        $currency_config = $CNT_ISO !== ''
220
            ? new EE_Currency_Config($CNT_ISO)
221
            : null;
222
        //default currency settings for site if not set
223 View Code Duplication
        if (! $currency_config instanceof EE_Currency_Config) {
224
            $currency_config = EE_Registry::instance()->CFG->currency instanceof EE_Currency_Config
225
                ? EE_Registry::instance()->CFG->currency
226
                : new EE_Currency_Config();
227
        }
228
        return $currency_config;
229
    }
230
231
} //end class EEH_Money
232