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