Merge pull request #17999 from eileenmcnaughton/sql_cache
[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)) {
ca4cfe7a
SL
142 $money = Money::of($leftOp, $currency, new DefaultContext(), RoundingMode::CEILING);
143 return $money->minus($rightOp)->getAmount()->toFloat();
c10c4749
EL
144 }
145 }
146
c16c6ad8
CR
147 /**
148 * Tests if two currency values are equal, taking into account the currency's
ecaa5b43 149 * precision, so that the two values are compared as integers after rounding.
c16c6ad8
CR
150 *
151 * Eg.
152 *
ecaa5b43
FW
153 * 1.231 == 1.232 with a currency precision of 2 decimal points
154 * 1.234 != 1.236 with a currency precision of 2 decimal points
155 * 1.300 != 1.200 with a currency precision of 2 decimal points
c16c6ad8
CR
156 *
157 * @param $value1
158 * @param $value2
159 * @param $currency
160 *
161 * @return bool
162 */
163 public static function equals($value1, $value2, $currency) {
ecaa5b43 164 $precision = pow(10, self::getCurrencyPrecision($currency));
c16c6ad8 165
ecaa5b43 166 return (int) round($value1 * $precision) == (int) round($value2 * $precision);
c16c6ad8
CR
167 }
168
28c249a9 169 /**
170 * Format money for display (just numeric part) according to the current locale.
171 *
172 * This calls the underlying system function but does not handle currency separators.
173 *
174 * It's not totally clear when it changes the $amount value but has historical usage.
175 *
176 * @param $amount
177 *
178 * @return string
179 */
180 protected static function formatLocaleNumeric($amount) {
9a894bf1
SL
181 if (CRM_Core_Config::singleton()->moneyvalueformat !== '%!i') {
182 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.');
183 }
28c249a9 184 return self::formatNumericByFormat($amount, CRM_Core_Config::singleton()->moneyvalueformat);
185 }
186
187 /**
188 * Format money for display (just numeric part) according to the current locale with rounding.
189 *
190 * At this stage this is conceived as an internal function with the currency wrapper
191 * functions determining the number of places.
192 *
193 * This calls the underlying system function but does not handle currency separators.
194 *
195 * It's not totally clear when it changes the $amount value but has historical usage.
196 *
197 * @param string $amount
198 * @param int $numberOfPlaces
199 *
200 * @return string
201 */
202 protected static function formatLocaleNumericRounded($amount, $numberOfPlaces) {
203 return self::formatLocaleNumeric(round($amount, $numberOfPlaces));
204 }
205
206 /**
207 * Format money for display (just numeric part) according to the current locale with rounding.
208 *
209 * This handles both rounding & replacement of the currency separators for the locale.
210 *
211 * @param string $amount
212 * @param string $currency
213 *
214 * @return string
215 * Formatted amount.
216 */
217 public static function formatLocaleNumericRoundedByCurrency($amount, $currency) {
218 $amount = self::formatLocaleNumericRounded($amount, self::getCurrencyPrecision($currency));
219 return self::replaceCurrencySeparators($amount);
220 }
221
222 /**
223 * Format money for display (just numeric part) according to the current locale with rounding based on the
224 * default currency for the site.
225 *
226 * @param $amount
227 * @return mixed
228 */
229 public static function formatLocaleNumericRoundedForDefaultCurrency($amount) {
230 return self::formatLocaleNumericRoundedByCurrency($amount, self::getCurrencyPrecision(CRM_Core_Config::singleton()->defaultCurrency));
231 }
232
233 /**
234 * Replace currency separators.
235 *
236 * @param string $amount
237 *
238 * @return string
239 */
240 protected static function replaceCurrencySeparators($amount) {
241 $config = CRM_Core_Config::singleton();
be2fb01f 242 $rep = [
28c249a9 243 ',' => $config->monetaryThousandSeparator,
244 '.' => $config->monetaryDecimalPoint,
be2fb01f 245 ];
28c249a9 246 return strtr($amount, $rep);
247 }
248
249 /**
250 * Format numeric part of currency by the passed in format.
251 *
252 * This is envisaged as an internal function, with wrapper functions defining valueFormat
253 * into easily understood functions / variables and handling separator conversions and
254 * rounding.
255 *
256 * @param string $amount
257 * @param string $valueFormat
258 *
259 * @return string
260 */
261 protected static function formatNumericByFormat($amount, $valueFormat) {
262 // money_format() exists only in certain PHP install (CRM-650)
263 // setlocale() affects native gettext (CRM-11054, CRM-9976)
264 if (is_numeric($amount) && function_exists('money_format')) {
265 $lc = setlocale(LC_MONETARY, 0);
266 setlocale(LC_MONETARY, 'en_US.utf8', 'en_US', 'en_US.utf8', 'en_US', 'C');
267 $amount = money_format($valueFormat, $amount);
268 setlocale(LC_MONETARY, $lc);
269 }
270 return $amount;
271 }
272
6a488035 273}