Merge pull request #19148 from civicrm/5.33
[civicrm-core.git] / CRM / Utils / Money.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 use Brick\Money\Money;
19 use Brick\Money\Context\DefaultContext;
20 use Brick\Money\Context\CustomContext;
21 use Brick\Math\RoundingMode;
22
23 /**
24 * Money utilties
25 */
26 class CRM_Utils_Money {
27 public static $_currencySymbols = NULL;
28
29 /**
30 * Format a monetary string.
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 *
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.
45 * @param bool $onlyNumber
46 * @param string $valueFormat
47 * The desired monetary value display format (e.g. '%!i').
48 *
49 * @return string
50 * formatted monetary string
51 *
52 */
53 public static function format($amount, $currency = NULL, $format = NULL, $onlyNumber = FALSE, $valueFormat = NULL) {
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 }
64
65 if (!$valueFormat) {
66 $valueFormat = $config->moneyvalueformat;
67 }
68
69 if (!empty($valueFormat) && $valueFormat !== '%!i') {
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;
75 }
76
77 if ($onlyNumber) {
78 $amount = self::formatLocaleNumericRoundedByCurrency($amount, $currency);
79 return $amount;
80 }
81
82 if (!self::$_currencySymbols) {
83 self::$_currencySymbols = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'currency', [
84 'keyColumn' => 'name',
85 'labelColumn' => 'symbol',
86 ]);
87 }
88
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
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
99 $amount = self::formatNumericByFormat($amount, $valueFormat);
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.
103 // @todo deprecate handling for the html tags because .... WTF
104 if (strpos($amount, '<') === FALSE) {
105 $amount = self::replaceCurrencySeparators($amount);
106 }
107
108 $replacements = [
109 '%a' => $amount,
110 '%C' => $currency,
111 '%c' => CRM_Utils_Array::value($currency, self::$_currencySymbols, $currency),
112 ];
113 return strtr($format, $replacements);
114 }
115
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
132 /**
133 * Subtract currencies using integers instead of floats, to preserve precision
134 *
135 * @param string|float $leftOp
136 * @param string|float $rightOp
137 * @param string $currency
138 *
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)) {
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();
147 }
148 }
149
150 /**
151 * Tests if two currency values are equal, taking into account the currency's
152 * precision, so that the two values are compared as integers after rounding.
153 *
154 * Eg.
155 *
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
159 *
160 * @param $value1
161 * @param $value2
162 * @param $currency
163 *
164 * @return bool
165 */
166 public static function equals($value1, $value2, $currency) {
167 $precision = pow(10, self::getCurrencyPrecision($currency));
168
169 return (int) round($value1 * $precision) == (int) round($value2 * $precision);
170 }
171
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) {
184 if (CRM_Core_Config::singleton()->moneyvalueformat !== '%!i') {
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.');
186 }
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) {
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);
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) {
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);
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();
288 $rep = [
289 ',' => $config->monetaryThousandSeparator,
290 '.' => $config->monetaryDecimalPoint,
291 ];
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
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
326 }