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