Merge pull request #18332 from totten/5.29-norm-basepage
[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\Math\RoundingMode;
21
22 /**
23 * Money utilties
24 */
25 class CRM_Utils_Money {
26 public static $_currencySymbols = NULL;
27
28 /**
29 * Format a monetary string.
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 *
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.
44 * @param bool $onlyNumber
45 * @param string $valueFormat
46 * The desired monetary value display format (e.g. '%!i').
47 *
48 * @return string
49 * formatted monetary string
50 *
51 */
52 public static function format($amount, $currency = NULL, $format = NULL, $onlyNumber = FALSE, $valueFormat = NULL) {
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 }
63
64 if (!$valueFormat) {
65 $valueFormat = $config->moneyvalueformat;
66 }
67
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
72 if ($onlyNumber) {
73 // money_format() exists only in certain PHP install (CRM-650)
74 if (is_numeric($amount) and function_exists('money_format')) {
75 $amount = money_format($valueFormat, $amount);
76 }
77 return $amount;
78 }
79
80 if (!self::$_currencySymbols) {
81 self::$_currencySymbols = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'currency', [
82 'keyColumn' => 'name',
83 'labelColumn' => 'symbol',
84 ]);
85 }
86
87 if (!$currency) {
88 $currency = $config->defaultCurrency;
89 }
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
97 $amount = self::formatNumericByFormat($amount, $valueFormat);
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.
101 // @todo deprecate handling for the html tags because .... WTF
102 if (strpos($amount, '<') === FALSE) {
103 $amount = self::replaceCurrencySeparators($amount);
104 }
105
106 $replacements = [
107 '%a' => $amount,
108 '%C' => $currency,
109 '%c' => CRM_Utils_Array::value($currency, self::$_currencySymbols, $currency),
110 ];
111 return strtr($format, $replacements);
112 }
113
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
130 /**
131 * Subtract currencies using integers instead of floats, to preserve precision
132 *
133 * @param string|float $leftOp
134 * @param string|float $rightOp
135 * @param string $currency
136 *
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)) {
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();
145 }
146 }
147
148 /**
149 * Tests if two currency values are equal, taking into account the currency's
150 * precision, so that the two values are compared as integers after rounding.
151 *
152 * Eg.
153 *
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
157 *
158 * @param $value1
159 * @param $value2
160 * @param $currency
161 *
162 * @return bool
163 */
164 public static function equals($value1, $value2, $currency) {
165 $precision = pow(10, self::getCurrencyPrecision($currency));
166
167 return (int) round($value1 * $precision) == (int) round($value2 * $precision);
168 }
169
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) {
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 }
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) {
204 return self::formatLocaleNumeric(round($amount, $numberOfPlaces));
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) {
219 $amount = self::formatLocaleNumericRounded($amount, self::getCurrencyPrecision($currency));
220 return self::replaceCurrencySeparators($amount);
221 }
222
223 /**
224 * Format money for display (just numeric part) according to the current locale with rounding based on the
225 * default currency for the site.
226 *
227 * @param $amount
228 * @return mixed
229 */
230 public static function formatLocaleNumericRoundedForDefaultCurrency($amount) {
231 return self::formatLocaleNumericRoundedByCurrency($amount, self::getCurrencyPrecision(CRM_Core_Config::singleton()->defaultCurrency));
232 }
233
234 /**
235 * Replace currency separators.
236 *
237 * @param string $amount
238 *
239 * @return string
240 */
241 protected static function replaceCurrencySeparators($amount) {
242 $config = CRM_Core_Config::singleton();
243 $rep = [
244 ',' => $config->monetaryThousandSeparator,
245 '.' => $config->monetaryDecimalPoint,
246 ];
247 return strtr($amount, $rep);
248 }
249
250 /**
251 * Format numeric part of currency by the passed in format.
252 *
253 * This is envisaged as an internal function, with wrapper functions defining valueFormat
254 * into easily understood functions / variables and handling separator conversions and
255 * rounding.
256 *
257 * @param string $amount
258 * @param string $valueFormat
259 *
260 * @return string
261 */
262 protected static function formatNumericByFormat($amount, $valueFormat) {
263 // money_format() exists only in certain PHP install (CRM-650)
264 // setlocale() affects native gettext (CRM-11054, CRM-9976)
265 if (is_numeric($amount) && function_exists('money_format')) {
266 $lc = setlocale(LC_MONETARY, 0);
267 setlocale(LC_MONETARY, 'en_US.utf8', 'en_US', 'en_US.utf8', 'en_US', 'C');
268 $amount = money_format($valueFormat, $amount);
269 setlocale(LC_MONETARY, $lc);
270 }
271 return $amount;
272 }
273
274 }