Completed
Branch BUG/11288/fix-datepicker (04df7b)
by
unknown
65:36 queued 52:18
created

EEH_Money::get_currency_config()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 14
Code Lines 9

Duplication

Lines 5
Ratio 35.71 %

Importance

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