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