Merge pull request #19438 from colemanw/afformDropAttrSupport
[civicrm-core.git] / CRM / Utils / Money.php
CommitLineData
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
18use Brick\Money\Money;
19use Brick\Money\Context\DefaultContext;
096110f3 20use Brick\Money\Context\CustomContext;
ca4cfe7a
SL
21use Brick\Math\RoundingMode;
22
6a488035
TO
23/**
24 * Money utilties
25 */
26class 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
77855840
TO
46 * @param string $valueFormat
47 * The desired monetary value display format (e.g. '%!i').
6a488035 48 *
a6c01b45
CW
49 * @return string
50 * formatted monetary string
6a488035 51 *
6a488035 52 */
00be9182 53 public static function format($amount, $currency = NULL, $format = NULL, $onlyNumber = FALSE, $valueFormat = NULL) {
6a488035
TO
54
55 if (CRM_Utils_System::isNull($amount)) {
56 return '';
57 }
58
59 $config = CRM_Core_Config::singleton();
60
61 if (!$format) {
62 $format = $config->moneyformat;
63 }
f4aaa82a 64
ec4da14d
DG
65 if (!$valueFormat) {
66 $valueFormat = $config->moneyvalueformat;
67 }
f4aaa82a 68
9a894bf1 69 if (!empty($valueFormat) && $valueFormat !== '%!i') {
e9dc5230
SL
70 CRM_Core_Error::deprecatedWarning('Having a Money Value format other than %!i is deprecated, please report this on the GitLab Issue https://lab.civicrm.org/dev/core/-/issues/1494 with the relevant moneyValueFormat you use.');
71 }
72
73 if (!$currency) {
74 $currency = $config->defaultCurrency;
9a894bf1
SL
75 }
76
6a488035 77 if ($onlyNumber) {
e9dc5230 78 $amount = self::formatLocaleNumericRoundedByCurrency($amount, $currency);
6a488035
TO
79 return $amount;
80 }
81
82 if (!self::$_currencySymbols) {
be2fb01f 83 self::$_currencySymbols = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'currency', [
6714d8d2
SL
84 'keyColumn' => 'name',
85 'labelColumn' => 'symbol',
86 ]);
6a488035
TO
87 }
88
5fb64d51
PF
89 // ensure $currency is a valid currency code
90 // for backwards-compatibility, also accept one space instead of a currency
91 if ($currency != ' ' && !array_key_exists($currency, self::$_currencySymbols)) {
92 throw new CRM_Core_Exception("Invalid currency \"{$currency}\"");
93 }
94
e9dc5230
SL
95 if ($currency === ' ') {
96 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');
97 }
98
28c249a9 99 $amount = self::formatNumericByFormat($amount, $valueFormat);
6a488035
TO
100 // If it contains tags, means that HTML was passed and the
101 // amount is already converted properly,
102 // so don't mess with it again.
28c249a9 103 // @todo deprecate handling for the html tags because .... WTF
6a488035 104 if (strpos($amount, '<') === FALSE) {
28c249a9 105 $amount = self::replaceCurrencySeparators($amount);
6a488035
TO
106 }
107
be2fb01f 108 $replacements = [
6a488035
TO
109 '%a' => $amount,
110 '%C' => $currency,
111 '%c' => CRM_Utils_Array::value($currency, self::$_currencySymbols, $currency),
be2fb01f 112 ];
6a488035
TO
113 return strtr($format, $replacements);
114 }
96025800 115
31f5f5e4
ML
116 /**
117 * This is a placeholder function for calculating the number of decimal places for a currency.
118 *
119 * Currently code assumes 2 decimal places but some currencies (bitcoin, middle eastern) have
120 * more. By using this function we can signpost the locations where the number of decimal places is
121 * currency specific for future enhancement.
122 *
123 * @param string $currency
124 *
125 * @return int
126 * Number of decimal places.
127 */
128 public static function getCurrencyPrecision($currency = NULL) {
129 return 2;
130 }
131
c10c4749
EL
132 /**
133 * Subtract currencies using integers instead of floats, to preserve precision
134 *
5ab2fd4f
MWMC
135 * @param string|float $leftOp
136 * @param string|float $rightOp
137 * @param string $currency
138 *
c10c4749
EL
139 * @return float
140 * Result of subtracting $rightOp from $leftOp to the precision of $currency
141 */
142 public static function subtractCurrencies($leftOp, $rightOp, $currency) {
143 if (is_numeric($leftOp) && is_numeric($rightOp)) {
f1b72041
CW
144 $leftMoney = Money::of($leftOp, $currency, new DefaultContext(), RoundingMode::CEILING);
145 $rightMoney = Money::of($rightOp, $currency, new DefaultContext(), RoundingMode::CEILING);
146 return $leftMoney->minus($rightMoney)->getAmount()->toFloat();
c10c4749
EL
147 }
148 }
149
c16c6ad8
CR
150 /**
151 * Tests if two currency values are equal, taking into account the currency's
ecaa5b43 152 * precision, so that the two values are compared as integers after rounding.
c16c6ad8
CR
153 *
154 * Eg.
155 *
ecaa5b43
FW
156 * 1.231 == 1.232 with a currency precision of 2 decimal points
157 * 1.234 != 1.236 with a currency precision of 2 decimal points
158 * 1.300 != 1.200 with a currency precision of 2 decimal points
c16c6ad8
CR
159 *
160 * @param $value1
161 * @param $value2
162 * @param $currency
163 *
164 * @return bool
165 */
166 public static function equals($value1, $value2, $currency) {
ecaa5b43 167 $precision = pow(10, self::getCurrencyPrecision($currency));
c16c6ad8 168
ecaa5b43 169 return (int) round($value1 * $precision) == (int) round($value2 * $precision);
c16c6ad8
CR
170 }
171
28c249a9 172 /**
173 * Format money for display (just numeric part) according to the current locale.
174 *
175 * This calls the underlying system function but does not handle currency separators.
176 *
177 * It's not totally clear when it changes the $amount value but has historical usage.
178 *
179 * @param $amount
180 *
181 * @return string
182 */
183 protected static function formatLocaleNumeric($amount) {
9a894bf1 184 if (CRM_Core_Config::singleton()->moneyvalueformat !== '%!i') {
e9dc5230 185 CRM_Core_Error::deprecatedWarning('Having a Money Value format other than !%i is deprecated, please report this on GitLab with the relevant moneyValueFormat you use.');
9a894bf1 186 }
28c249a9 187 return self::formatNumericByFormat($amount, CRM_Core_Config::singleton()->moneyvalueformat);
188 }
189
190 /**
191 * Format money for display (just numeric part) according to the current locale with rounding.
192 *
193 * At this stage this is conceived as an internal function with the currency wrapper
194 * functions determining the number of places.
195 *
196 * This calls the underlying system function but does not handle currency separators.
197 *
198 * It's not totally clear when it changes the $amount value but has historical usage.
199 *
200 * @param string $amount
201 * @param int $numberOfPlaces
202 *
203 * @return string
204 */
205 protected static function formatLocaleNumericRounded($amount, $numberOfPlaces) {
096110f3
SL
206 if (!extension_loaded('intl')) {
207 self::missingIntlNotice();
208 return self::formatNumericByFormat($amount, '%!.' . $numberOfPlaces . 'i');
209 }
210 $money = Money::of($amount, CRM_Core_Config::singleton()->defaultCurrency, new CustomContext($numberOfPlaces), RoundingMode::CEILING);
211 $formatter = new \NumberFormatter(CRM_Core_I18n::getLocale(), NumberFormatter::CURRENCY);
212 $formatter->setSymbol(\NumberFormatter::CURRENCY_SYMBOL, '');
213 $formatter->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, $numberOfPlaces);
214 return $money->formatWith($formatter);
28c249a9 215 }
216
217 /**
218 * Format money for display (just numeric part) according to the current locale with rounding.
219 *
220 * This handles both rounding & replacement of the currency separators for the locale.
221 *
222 * @param string $amount
223 * @param string $currency
224 *
225 * @return string
226 * Formatted amount.
227 */
228 public static function formatLocaleNumericRoundedByCurrency($amount, $currency) {
c9763347 229 return self::formatLocaleNumericRoundedByPrecision($amount, self::getCurrencyPrecision($currency));
230 }
231
232 /**
233 * Format money for display (just numeric part) according to the current locale with rounding to the supplied precision.
234 *
235 * This handles both rounding & replacement of the currency separators for the locale.
236 *
237 * @param string $amount
238 * @param int $precision
239 *
240 * @return string
241 * Formatted amount.
242 */
243 public static function formatLocaleNumericRoundedByPrecision($amount, $precision) {
244 $amount = self::formatLocaleNumericRounded($amount, $precision);
245 return self::replaceCurrencySeparators($amount);
246 }
247
248 /**
249 * Format money for display with rounding to the supplied precision but without padding.
250 *
251 * If the string is shorter than the precision trailing zeros are not added to reach the precision
252 * beyond the 2 required for normally currency formatting.
253 *
254 * This handles both rounding & replacement of the currency separators for the locale.
255 *
256 * @param string $amount
257 * @param int $precision
258 *
259 * @return string
260 * Formatted amount.
261 */
262 public static function formatLocaleNumericRoundedByOptionalPrecision($amount, $precision) {
263 $decimalPlaces = strlen(substr($amount, strpos($amount, '.') + 1));
264 $amount = self::formatLocaleNumericRounded($amount, $precision > $decimalPlaces ? $decimalPlaces : $precision);
28c249a9 265 return self::replaceCurrencySeparators($amount);
266 }
267
268 /**
269 * Format money for display (just numeric part) according to the current locale with rounding based on the
270 * default currency for the site.
271 *
272 * @param $amount
273 * @return mixed
274 */
275 public static function formatLocaleNumericRoundedForDefaultCurrency($amount) {
276 return self::formatLocaleNumericRoundedByCurrency($amount, self::getCurrencyPrecision(CRM_Core_Config::singleton()->defaultCurrency));
277 }
278
279 /**
280 * Replace currency separators.
281 *
282 * @param string $amount
283 *
284 * @return string
285 */
286 protected static function replaceCurrencySeparators($amount) {
287 $config = CRM_Core_Config::singleton();
be2fb01f 288 $rep = [
28c249a9 289 ',' => $config->monetaryThousandSeparator,
290 '.' => $config->monetaryDecimalPoint,
be2fb01f 291 ];
28c249a9 292 return strtr($amount, $rep);
293 }
294
295 /**
296 * Format numeric part of currency by the passed in format.
297 *
298 * This is envisaged as an internal function, with wrapper functions defining valueFormat
299 * into easily understood functions / variables and handling separator conversions and
300 * rounding.
301 *
302 * @param string $amount
303 * @param string $valueFormat
304 *
305 * @return string
306 */
307 protected static function formatNumericByFormat($amount, $valueFormat) {
308 // money_format() exists only in certain PHP install (CRM-650)
309 // setlocale() affects native gettext (CRM-11054, CRM-9976)
310 if (is_numeric($amount) && function_exists('money_format')) {
311 $lc = setlocale(LC_MONETARY, 0);
312 setlocale(LC_MONETARY, 'en_US.utf8', 'en_US', 'en_US.utf8', 'en_US', 'C');
313 $amount = money_format($valueFormat, $amount);
314 setlocale(LC_MONETARY, $lc);
315 }
316 return $amount;
317 }
318
096110f3
SL
319 /**
320 * Emits a notice indicating we have fallen back to a less accurate way of formatting money due to missing intl extension
321 */
322 public static function missingIntlNotice() {
323 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'));
324 }
325
6a488035 326}