-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMoney.php
556 lines (500 loc) · 14.5 KB
/
Money.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
<?php
namespace Money;
use InvalidArgumentException;
use JsonSerializable;
use OverflowException;
use UnderflowException;
/**
* Value Object that represents a monetary value
* (using a currency's smallest unit).
*
* This file is inspired by the Money package, by Sebastian Bergmann
* and the money solution by Martin Fowler.
*
* @see http://www.github.com/sebastianbergmann/money
* @see http://martinfowler.com/bliki/ValueObject.html
* @see http://martinfowler.com/eaaCatalog/money.html
*
* @psalm-immutable
*/
final class Money implements JsonSerializable
{
/**
* @var int[]
*/
private const ROUNDING_MODES = [
PHP_ROUND_HALF_UP,
PHP_ROUND_HALF_DOWN,
PHP_ROUND_HALF_EVEN,
PHP_ROUND_HALF_ODD,
];
/**
* @var int
*/
private $amount;
/**
* @var Currency
*/
private $currency;
/**
* @param int $amount
* @param Currency $currency
*
* @throws InvalidArgumentException
*/
public function __construct(int $amount, Currency $currency)
{
$this->amount = $amount;
$this->currency = $currency;
}
/**
* Creates a Money object from a string such as "12.34".
*
* This method is designed to take into account the errors that can arise
* from manipulating floating point numbers.
*
* If the number of decimals in the string is higher than the currency's
* number of fractional digits then the value will be rounded to the
* currency's number of fractional digits.
*
* @psalm-pure
*
* @param float|int|object|string $value
* @param Currency|string $currency
*
* @throws InvalidArgumentException
*
* @return self
*/
public static function fromString($value, $currency): self
{
if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
throw new InvalidArgumentException('$value must be a string');
}
if (!is_string($currency) && !(is_object($currency) && method_exists($currency, '__toString'))) {
throw new InvalidArgumentException('$currency must be a string');
}
$value = (string) $value;
$currency = new Currency((string) $currency);
return new self(
(int) (
round(
$currency->getSubUnit() *
round(
(float) $value,
$currency->getDefaultFractionDigits(),
PHP_ROUND_HALF_UP
),
0,
PHP_ROUND_HALF_UP
)
),
$currency
);
}
/**
* {@inheritdoc}
*/
public function jsonSerialize(): array
{
return [
'amount' => $this->getAmount(),
'currency' => $this->getCurrency()->jsonSerialize(),
];
}
/**
* Returns the monetary value represented by this object.
*
* @return int
*/
public function getAmount(): int
{
return $this->amount;
}
/**
* Returns the monetary value represented by this object converted to its base units.
*
* @return float
*/
public function getConvertedAmount(): float
{
return round(
$this->getAmount() / $this->getCurrency()->getSubUnit(),
$this->getCurrency()->getDefaultFractionDigits(),
PHP_ROUND_HALF_UP
);
}
/**
* Formats the monetary value to string.
*
* @param string $decimalPoint
* @param string $thousandsSeparator
*
* @return string
*/
public function getFormattedAmount(string $decimalPoint = '.', string $thousandsSeparator = ','): string
{
return number_format(
$this->getConvertedAmount(),
$this->getCurrency()->getDefaultFractionDigits(),
$decimalPoint,
$thousandsSeparator
);
}
/**
* Formats the given value to be displayed with its symbol and fractions.
*
* There is lack the information about currency symbol position,
* so it's placed as for USD and many others before amount.
*
* @param string $decimalPoint
* @param string $thousandsSeparator
* @param bool $withCurrencyCode
*
* @return string
*/
public function getPrettyPrint(
string $decimalPoint = '.',
string $thousandsSeparator = ',',
bool $withCurrencyCode = false
): string {
$currencySign = $this->getCurrency()->getSign();
$formattedAmount = ltrim($this->getFormattedAmount($decimalPoint, $thousandsSeparator), '-');
$amountSign = $this->isNegative() ? '-' : '';
$currencyCode = $withCurrencyCode ? " {$this->getCurrency()->getCurrencyCode()}" : '';
return "{$amountSign}{$currencySign}{$formattedAmount}{$currencyCode}";
}
/**
* Returns the currency of the monetary value represented by this object.
*
* @return Currency
*/
public function getCurrency(): Currency
{
return $this->currency;
}
/**
* Returns a new Money object that represents the monetary value
* of the sum of this Money object and another.
*
* @param self $other
*
* @throws CurrencyMismatchException
* @throws OverflowException
*
* @return self
*/
public function add(self $other): self
{
$value = $this->getAmount() + $this->castOtherAmountToInt($other);
if (!is_int($value)) {
throw new OverflowException('Value reached maximum amount');
}
return $this->changeAmount($value);
}
/**
* Returns a new Money object that represents the monetary value
* of the difference of this Money object and another.
*
* @param self $other
*
* @throws CurrencyMismatchException
* @throws OverflowException
*
* @return self
*/
public function subtract(self $other): self
{
$value = $this->getAmount() - $this->castOtherAmountToInt($other);
if (!is_int($value)) {
throw new UnderflowException('Value reached minimum amount');
}
return $this->changeAmount($value);
}
/**
* Returns a new Money object that represents the negated monetary value
* of this Money object.
*
* @return self
*/
public function negate(): self
{
return $this->changeAmount(-1 * $this->getAmount());
}
/**
* Returns a new Money object that represents the monetary value
* of this Money object multiplied by a given factor.
*
* @param float $factor
* @param int $roundingMode
*
* @throws InvalidArgumentException
*
* @return self
*/
public function multiply(float $factor, int $roundingMode = PHP_ROUND_HALF_UP): self
{
return $this->changeFloatAmount($this->roundValueByMode($factor * $this->getAmount(), $roundingMode));
}
/**
* Allocate the monetary value represented by this Money object
* among N targets.
*
* @param int $n
*
* @throws InvalidArgumentException
*
* @return self[]
*/
public function allocateToTargets(int $n): array
{
if ($n === 0) {
throw new InvalidArgumentException('$n must not be zero');
}
$sign = ($this->getAmount() < 0) ? -1 : 1;
$amount = abs($this->getAmount());
$low = $this->changeAmount((int) ($amount / $n));
$high = $this->changeAmount($low->getAmount() + 1);
$remainder = $amount % $n;
$result = [];
for ($i = 0; $i < $remainder; ++$i) {
$result[] = $high->multiply($sign);
}
for ($i = $remainder; $i < $n; ++$i) {
$result[] = $low->multiply($sign);
}
return $result;
}
/**
* Allocate the monetary value represented by this Money object
* using a list of ratios.
*
* @param array<float|int> $ratios
*
* @return self[]
*/
public function allocateByRatios(array $ratios): array
{
$total = array_sum($ratios);
if ($total === 0.0 || $total === 0) {
throw new InvalidArgumentException('The ratios sum must not be zero');
}
$result = [];
$sign = $this->isNegative() ? -1 : 1;
$absAmount = abs($this->getAmount());
$remainder = $absAmount;
foreach ($ratios as $ratio) {
$money = $this->changeFloatAmount($absAmount * $ratio / $total * $sign);
$remainder -= abs($money->getAmount());
$result[] = $money;
}
for ($i = 0; $i < $remainder; ++$i) {
$result[$i] = $this->changeAmount($result[$i]->getAmount() + $sign);
}
return $result;
}
/**
* Extracts a percentage of the monetary value represented by this Money
* object and returns an array of two Money objects:
* $original = $result['subtotal'] + $result['percentage'];.
*
* Please note that this extracts the percentage out of a monetary value
* where the percentage is already included. If you want to get the
* percentage of the monetary value you should use multiplication
* (multiply(0.21), for instance, to calculate 21% of a monetary value
* represented by a Money object) instead.
*
* @see https://github.com/sebastianbergmann/money/issues/27
*
* @param float|int $percentage
* @param int $roundingMode
*
* @return self[]
*/
public function extractPercentage($percentage, int $roundingMode = PHP_ROUND_HALF_UP): array
{
$amount = round($this->getAmount() / (100 + $percentage) * $percentage, 0, $roundingMode);
$percentage = $this->changeFloatAmount($amount);
return [
'percentage' => $percentage,
'subtotal' => $this->subtract($percentage),
];
}
/**
* Compares this Money object to another.
*
* Returns an integer less than, equal to, or greater than zero
* if the value of this Money object is considered to be respectively
* less than, equal to, or greater than the other Money object.
*
* @param self $other
*
* @throws CurrencyMismatchException
*
* @return int -1|0|1
*/
public function compareTo(self $other): int
{
return $this->getAmount() <=> $this->castOtherAmountToInt($other);
}
/**
* Returns TRUE if this Money object equals to another.
*
* @param self $other
*
* @throws CurrencyMismatchException
*
* @return bool
*/
public function equals(self $other): bool
{
return $this->getCurrency()->equals($other->getCurrency()) && $this->compareTo($other) === 0;
}
/**
* Returns TRUE if the monetary value represented by this Money object
* is greater than that of another, FALSE otherwise.
*
* @param self $other
*
* @throws CurrencyMismatchException
*
* @return bool
*/
public function greaterThan(self $other): bool
{
return $this->compareTo($other) === 1;
}
/**
* Returns TRUE if the monetary value represented by this Money object
* is greater than or equal that of another, FALSE otherwise.
*
* @param self $other
*
* @throws CurrencyMismatchException
*
* @return bool
*/
public function greaterThanOrEqual(self $other): bool
{
return $this->greaterThan($other) || $this->equals($other);
}
/**
* Returns TRUE if the monetary value represented by this Money object
* is smaller than that of another, FALSE otherwise.
*
* @param self $other
*
* @throws CurrencyMismatchException
*
* @return bool
*/
public function lessThan(self $other): bool
{
return $this->compareTo($other) === -1;
}
/**
* Returns TRUE if the monetary value represented by this Money object
* is smaller than or equal that of another, FALSE otherwise.
*
* @param self $other
*
* @throws CurrencyMismatchException
*
* @return bool
*/
public function lessThanOrEqual(self $other): bool
{
return $this->lessThan($other) || $this->equals($other);
}
/**
* @return bool
*/
public function isZero(): bool
{
return $this->getAmount() === 0;
}
/**
* @return bool
*/
public function isPositive(): bool
{
return $this->getAmount() > 0;
}
/**
* @return bool
*/
public function isNegative(): bool
{
return $this->getAmount() < 0;
}
/**
* Convert currency to a target currency given a conversion rate and rounding mode.
*
* @param Currency $targetCurrency
* @param float $conversionRate
* @param int $roundingMode
*
* @return self
*/
public function convert(Currency $targetCurrency, float $conversionRate, int $roundingMode): self
{
return new self(
$this->castToInt($this->roundValueByMode($conversionRate * $this->getAmount(), $roundingMode)),
$targetCurrency,
);
}
/**
* @param float|int $value
* @param int $roundingMode
*
* @return float
*/
private function roundValueByMode($value, int $roundingMode): float
{
if (!in_array($roundingMode, self::ROUNDING_MODES, true)) {
throw new InvalidArgumentException('$roundingMode must be a valid rounding mode (PHP_ROUND_*)');
}
return round($value, 0, $roundingMode);
}
private function castOtherAmountToInt(self $amount): int
{
if (!$this->getCurrency()->equals($amount->getCurrency())) {
throw new CurrencyMismatchException();
}
return $amount->getAmount();
}
/**
* Cast an amount to an integer but ensure that the operation won't hide overflow.
*
* @param float $amount
*
* @throws OverflowException
*
* @return int
*/
private function castToInt(float $amount): int
{
if (abs($amount) > PHP_INT_MAX) {
throw new OverflowException();
}
return (int) $amount;
}
/**
* @param int $amount
*
* @return self
*/
private function changeAmount(int $amount): self
{
return new self($amount, $this->getCurrency());
}
/**
* @param float $amount
*
* @return self
*/
private function changeFloatAmount(float $amount): self
{
return $this->changeAmount($this->castToInt($amount));
}
}