Commit | Line | Data |
---|---|---|
6a488035 TO |
1 | <?php |
2 | /* | |
3 | +--------------------------------------------------------------------+ | |
bc77d7c0 | 4 | | Copyright CiviCRM LLC. All rights reserved. | |
6a488035 | 5 | | | |
bc77d7c0 TO |
6 | | This work is published under the GNU AGPLv3 license with some | |
7 | | permitted exceptions and without any warranty. For full license | | |
8 | | and copyright information, see https://civicrm.org/licensing | | |
6a488035 | 9 | +--------------------------------------------------------------------+ |
d25dd0ee | 10 | */ |
6a488035 TO |
11 | |
12 | /** | |
13 | * | |
14 | * @package CRM | |
ca5cec67 | 15 | * @copyright CiviCRM LLC https://civicrm.org/licensing |
6a488035 TO |
16 | */ |
17 | ||
ca4cfe7a SL |
18 | use Brick\Money\Money; |
19 | use Brick\Money\Context\DefaultContext; | |
096110f3 | 20 | use Brick\Money\Context\CustomContext; |
ca4cfe7a SL |
21 | use Brick\Math\RoundingMode; |
22 | ||
6a488035 TO |
23 | /** |
24 | * Money utilties | |
25 | */ | |
26 | class CRM_Utils_Money { | |
6714d8d2 | 27 | public static $_currencySymbols = NULL; |
6a488035 TO |
28 | |
29 | /** | |
fe482240 | 30 | * Format a monetary string. |
6a488035 TO |
31 | * |
32 | * Format a monetary string basing on the amount provided, | |
33 | * ISO currency code provided and a format string consisting of: | |
34 | * | |
35 | * %a - the formatted amount | |
36 | * %C - the currency ISO code (e.g., 'USD') if provided | |
37 | * %c - the currency symbol (e.g., '$') if available | |
38 | * | |
77855840 TO |
39 | * @param float $amount |
40 | * The monetary amount to display (1234.56). | |
41 | * @param string $currency | |
42 | * The three-letter ISO currency code ('USD'). | |
43 | * @param string $format | |
44 | * The desired currency format. | |
f4aaa82a | 45 | * @param bool $onlyNumber |
6a488035 | 46 | * |
a6c01b45 CW |
47 | * @return string |
48 | * formatted monetary string | |
6a488035 | 49 | * |
6a488035 | 50 | */ |
f15ba5a8 | 51 | public static function format($amount, $currency = NULL, $format = NULL, $onlyNumber = FALSE) { |
6a488035 TO |
52 | |
53 | if (CRM_Utils_System::isNull($amount)) { | |
54 | return ''; | |
55 | } | |
56 | ||
57 | $config = CRM_Core_Config::singleton(); | |
58 | ||
59 | if (!$format) { | |
60 | $format = $config->moneyformat; | |
61 | } | |
f4aaa82a | 62 | |
e9dc5230 SL |
63 | if (!$currency) { |
64 | $currency = $config->defaultCurrency; | |
9a894bf1 SL |
65 | } |
66 | ||
6a488035 | 67 | if ($onlyNumber) { |
e9dc5230 | 68 | $amount = self::formatLocaleNumericRoundedByCurrency($amount, $currency); |
6a488035 TO |
69 | return $amount; |
70 | } | |
71 | ||
72 | if (!self::$_currencySymbols) { | |
be2fb01f | 73 | self::$_currencySymbols = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'currency', [ |
6714d8d2 SL |
74 | 'keyColumn' => 'name', |
75 | 'labelColumn' => 'symbol', | |
76 | ]); | |
6a488035 TO |
77 | } |
78 | ||
5fb64d51 PF |
79 | // ensure $currency is a valid currency code |
80 | // for backwards-compatibility, also accept one space instead of a currency | |
81 | if ($currency != ' ' && !array_key_exists($currency, self::$_currencySymbols)) { | |
82 | throw new CRM_Core_Exception("Invalid currency \"{$currency}\""); | |
83 | } | |
84 | ||
e9dc5230 SL |
85 | if ($currency === ' ') { |
86 | CRM_Core_Error::deprecatedWarning('Passing empty currency to CRM_Utils_Money::format is deprecated if you need it for display without currency call CRM_Utils_Money::formatLocaleNumericRounded'); | |
87 | } | |
741608a9 | 88 | $amount = self::formatUSLocaleNumericRounded($amount, 2); |
6a488035 TO |
89 | // If it contains tags, means that HTML was passed and the |
90 | // amount is already converted properly, | |
91 | // so don't mess with it again. | |
28c249a9 | 92 | // @todo deprecate handling for the html tags because .... WTF |
6a488035 | 93 | if (strpos($amount, '<') === FALSE) { |
28c249a9 | 94 | $amount = self::replaceCurrencySeparators($amount); |
6a488035 TO |
95 | } |
96 | ||
be2fb01f | 97 | $replacements = [ |
6a488035 TO |
98 | '%a' => $amount, |
99 | '%C' => $currency, | |
100 | '%c' => CRM_Utils_Array::value($currency, self::$_currencySymbols, $currency), | |
be2fb01f | 101 | ]; |
6a488035 TO |
102 | return strtr($format, $replacements); |
103 | } | |
96025800 | 104 | |
31f5f5e4 ML |
105 | /** |
106 | * This is a placeholder function for calculating the number of decimal places for a currency. | |
107 | * | |
108 | * Currently code assumes 2 decimal places but some currencies (bitcoin, middle eastern) have | |
109 | * more. By using this function we can signpost the locations where the number of decimal places is | |
110 | * currency specific for future enhancement. | |
111 | * | |
112 | * @param string $currency | |
113 | * | |
114 | * @return int | |
115 | * Number of decimal places. | |
116 | */ | |
117 | public static function getCurrencyPrecision($currency = NULL) { | |
118 | return 2; | |
119 | } | |
120 | ||
c10c4749 EL |
121 | /** |
122 | * Subtract currencies using integers instead of floats, to preserve precision | |
123 | * | |
5ab2fd4f MWMC |
124 | * @param string|float $leftOp |
125 | * @param string|float $rightOp | |
126 | * @param string $currency | |
127 | * | |
c10c4749 EL |
128 | * @return float |
129 | * Result of subtracting $rightOp from $leftOp to the precision of $currency | |
130 | */ | |
131 | public static function subtractCurrencies($leftOp, $rightOp, $currency) { | |
132 | if (is_numeric($leftOp) && is_numeric($rightOp)) { | |
f1b72041 CW |
133 | $leftMoney = Money::of($leftOp, $currency, new DefaultContext(), RoundingMode::CEILING); |
134 | $rightMoney = Money::of($rightOp, $currency, new DefaultContext(), RoundingMode::CEILING); | |
135 | return $leftMoney->minus($rightMoney)->getAmount()->toFloat(); | |
c10c4749 EL |
136 | } |
137 | } | |
138 | ||
c16c6ad8 CR |
139 | /** |
140 | * Tests if two currency values are equal, taking into account the currency's | |
ecaa5b43 | 141 | * precision, so that the two values are compared as integers after rounding. |
c16c6ad8 CR |
142 | * |
143 | * Eg. | |
144 | * | |
ecaa5b43 FW |
145 | * 1.231 == 1.232 with a currency precision of 2 decimal points |
146 | * 1.234 != 1.236 with a currency precision of 2 decimal points | |
147 | * 1.300 != 1.200 with a currency precision of 2 decimal points | |
c16c6ad8 CR |
148 | * |
149 | * @param $value1 | |
150 | * @param $value2 | |
151 | * @param $currency | |
152 | * | |
153 | * @return bool | |
154 | */ | |
155 | public static function equals($value1, $value2, $currency) { | |
ecaa5b43 | 156 | $precision = pow(10, self::getCurrencyPrecision($currency)); |
c16c6ad8 | 157 | |
ecaa5b43 | 158 | return (int) round($value1 * $precision) == (int) round($value2 * $precision); |
c16c6ad8 CR |
159 | } |
160 | ||
28c249a9 | 161 | /** |
162 | * Format money for display (just numeric part) according to the current locale. | |
163 | * | |
164 | * This calls the underlying system function but does not handle currency separators. | |
165 | * | |
166 | * It's not totally clear when it changes the $amount value but has historical usage. | |
167 | * | |
168 | * @param $amount | |
169 | * | |
170 | * @return string | |
171 | */ | |
172 | protected static function formatLocaleNumeric($amount) { | |
f15ba5a8 | 173 | return self::formatNumericByFormat($amount); |
28c249a9 | 174 | } |
175 | ||
176 | /** | |
177 | * Format money for display (just numeric part) according to the current locale with rounding. | |
178 | * | |
179 | * At this stage this is conceived as an internal function with the currency wrapper | |
180 | * functions determining the number of places. | |
181 | * | |
182 | * This calls the underlying system function but does not handle currency separators. | |
183 | * | |
184 | * It's not totally clear when it changes the $amount value but has historical usage. | |
185 | * | |
741608a9 | 186 | * @param string|float $amount |
28c249a9 | 187 | * @param int $numberOfPlaces |
188 | * | |
189 | * @return string | |
190 | */ | |
741608a9 | 191 | protected static function formatUSLocaleNumericRounded($amount, int $numberOfPlaces): string { |
192 | if (!extension_loaded('intl') || !is_numeric($amount)) { | |
193 | // @todo - we should not attempt to format non-numeric strings. For now | |
194 | // these will not fail but will give notices on php 7.4 | |
7652b05f | 195 | if (!is_numeric($amount)) { |
196 | CRM_Core_Error::deprecatedWarning('Formatting non-numeric values is no longer supported: ' . htmlspecialchars($amount)); | |
197 | } | |
198 | else { | |
199 | self::missingIntlNotice(); | |
200 | } | |
096110f3 SL |
201 | return self::formatNumericByFormat($amount, '%!.' . $numberOfPlaces . 'i'); |
202 | } | |
741608a9 | 203 | $money = Money::of($amount, CRM_Core_Config::singleton()->defaultCurrency, new CustomContext($numberOfPlaces), RoundingMode::HALF_UP); |
136473f4 | 204 | // @todo - we specify en_US here because we don't want this function to do |
205 | // currency replacement at the moment because | |
206 | // formatLocaleNumericRoundedByPrecision is doing it and if it | |
207 | // is done there then it is swapped back in there.. This is a short term | |
208 | // fix to allow us to resolve formatLocaleNumericRoundedByPrecision | |
209 | // and to make the function comments correct - but, we need to reconsider this | |
210 | // in master as it is probably better to use locale than our currency separator fields. | |
78bafaf0 | 211 | $formatter = new \NumberFormatter('en_US', NumberFormatter::DECIMAL); |
096110f3 SL |
212 | $formatter->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, $numberOfPlaces); |
213 | return $money->formatWith($formatter); | |
28c249a9 | 214 | } |
215 | ||
216 | /** | |
217 | * Format money for display (just numeric part) according to the current locale with rounding. | |
218 | * | |
219 | * This handles both rounding & replacement of the currency separators for the locale. | |
220 | * | |
221 | * @param string $amount | |
222 | * @param string $currency | |
223 | * | |
224 | * @return string | |
225 | * Formatted amount. | |
226 | */ | |
227 | public static function formatLocaleNumericRoundedByCurrency($amount, $currency) { | |
c9763347 | 228 | return self::formatLocaleNumericRoundedByPrecision($amount, self::getCurrencyPrecision($currency)); |
229 | } | |
230 | ||
231 | /** | |
232 | * Format money for display (just numeric part) according to the current locale with rounding to the supplied precision. | |
233 | * | |
234 | * This handles both rounding & replacement of the currency separators for the locale. | |
235 | * | |
236 | * @param string $amount | |
237 | * @param int $precision | |
238 | * | |
239 | * @return string | |
240 | * Formatted amount. | |
241 | */ | |
242 | public static function formatLocaleNumericRoundedByPrecision($amount, $precision) { | |
741608a9 | 243 | $amount = self::formatUSLocaleNumericRounded($amount, $precision); |
c9763347 | 244 | return self::replaceCurrencySeparators($amount); |
245 | } | |
246 | ||
247 | /** | |
248 | * Format money for display with rounding to the supplied precision but without padding. | |
249 | * | |
250 | * If the string is shorter than the precision trailing zeros are not added to reach the precision | |
251 | * beyond the 2 required for normally currency formatting. | |
252 | * | |
253 | * This handles both rounding & replacement of the currency separators for the locale. | |
254 | * | |
255 | * @param string $amount | |
256 | * @param int $precision | |
257 | * | |
258 | * @return string | |
259 | * Formatted amount. | |
260 | */ | |
261 | public static function formatLocaleNumericRoundedByOptionalPrecision($amount, $precision) { | |
741608a9 | 262 | $decimalPlaces = self::getDecimalPlacesForAmount((string) $amount); |
263 | $amount = self::formatUSLocaleNumericRounded($amount, $precision > $decimalPlaces ? $decimalPlaces : $precision); | |
28c249a9 | 264 | return self::replaceCurrencySeparators($amount); |
265 | } | |
266 | ||
267 | /** | |
268 | * Format money for display (just numeric part) according to the current locale with rounding based on the | |
269 | * default currency for the site. | |
270 | * | |
271 | * @param $amount | |
272 | * @return mixed | |
273 | */ | |
274 | public static function formatLocaleNumericRoundedForDefaultCurrency($amount) { | |
275 | return self::formatLocaleNumericRoundedByCurrency($amount, self::getCurrencyPrecision(CRM_Core_Config::singleton()->defaultCurrency)); | |
276 | } | |
277 | ||
278 | /** | |
279 | * Replace currency separators. | |
280 | * | |
281 | * @param string $amount | |
282 | * | |
283 | * @return string | |
284 | */ | |
285 | protected static function replaceCurrencySeparators($amount) { | |
286 | $config = CRM_Core_Config::singleton(); | |
be2fb01f | 287 | $rep = [ |
28c249a9 | 288 | ',' => $config->monetaryThousandSeparator, |
289 | '.' => $config->monetaryDecimalPoint, | |
be2fb01f | 290 | ]; |
28c249a9 | 291 | return strtr($amount, $rep); |
292 | } | |
293 | ||
294 | /** | |
295 | * Format numeric part of currency by the passed in format. | |
296 | * | |
297 | * This is envisaged as an internal function, with wrapper functions defining valueFormat | |
298 | * into easily understood functions / variables and handling separator conversions and | |
299 | * rounding. | |
300 | * | |
301 | * @param string $amount | |
302 | * @param string $valueFormat | |
303 | * | |
304 | * @return string | |
305 | */ | |
f15ba5a8 | 306 | protected static function formatNumericByFormat($amount, $valueFormat = '%!i') { |
28c249a9 | 307 | // money_format() exists only in certain PHP install (CRM-650) |
308 | // setlocale() affects native gettext (CRM-11054, CRM-9976) | |
309 | if (is_numeric($amount) && function_exists('money_format')) { | |
310 | $lc = setlocale(LC_MONETARY, 0); | |
311 | setlocale(LC_MONETARY, 'en_US.utf8', 'en_US', 'en_US.utf8', 'en_US', 'C'); | |
312 | $amount = money_format($valueFormat, $amount); | |
313 | setlocale(LC_MONETARY, $lc); | |
314 | } | |
315 | return $amount; | |
316 | } | |
317 | ||
096110f3 SL |
318 | /** |
319 | * Emits a notice indicating we have fallen back to a less accurate way of formatting money due to missing intl extension | |
320 | */ | |
321 | public static function missingIntlNotice() { | |
322 | CRM_Core_Session::singleton()->setStatus(ts('As this system does not include the PHP intl extension, CiviCRM has fallen back onto a slightly less accurate and deprecated method to format money'), ts('Missing PHP INTL extension')); | |
323 | } | |
324 | ||
741608a9 | 325 | /** |
326 | * Get the number of characters after the decimal point. | |
327 | * | |
328 | * @param string $amount | |
329 | * | |
330 | * @return int | |
331 | */ | |
332 | protected static function getDecimalPlacesForAmount(string $amount): int { | |
333 | $decimalPlaces = strlen(substr($amount, strpos($amount, '.') + 1)); | |
334 | return $decimalPlaces; | |
335 | } | |
336 | ||
6a488035 | 337 | } |