Merge pull request #16482 from eileenmcnaughton/super-perm
[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::formatNumericByFormat($amount, '%!.' . $numberOfPlaces . 'i');
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 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);
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();
278 $rep = [
279 ',' => $config->monetaryThousandSeparator,
280 '.' => $config->monetaryDecimalPoint,
281 ];
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
309 }