This repository has been archived by the owner on Dec 15, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAmount.php
444 lines (396 loc) · 12.8 KB
/
Amount.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
<?php
declare(strict_types = 1);
namespace byrokrat\amount;
/**
* Value class for working with and representing monetary amounts
*
* Uses the bcmath extension for arbitrary floating point arithmetic precision
*/
class Amount
{
/**
* @var string
*/
private $amount;
/**
* @var array Substitution map for signal strings
*/
private static $signals = [
'0'=>'å', '1'=>'J', '2'=>'K', '3'=>'L', '4'=>'M', '5'=>'N', '6'=>'O', '7'=>'P', '8'=>'Q', '9'=>'R'
];
/**
* Create amount from numerical string
*
* @throws InvalidArgumentException If $amount is not valid
*/
public function __construct(string $amount)
{
if (!preg_match("/^[+-]?\d*\.?\d*$/", $amount)) {
throw new InvalidArgumentException("Constructor expects a numerical string");
}
$this->amount = $amount;
}
/**
* Create amount from integer or floating point number
*
* It is important to note that computers internally use the binary floating
* point format and cannot accurately represent a number like 0.1, 0.2 or
* 0.3 at all. Using floating point numbers leads to a loss of precision.
* For example `floor((0.1+0.7)*10)` will usually return 7 instead of the
* expected 8, since the internal representation will be something like
* 7.9999999999999991118....
*
* For this reason floats should never ne used to store monetary data. This
* method exists for rare situations when converting from native formats is
* inevitable. Unless you know what you are doing it should NOT be used.
*
* @param int|float $number
* @throws InvalidArgumentException If $number is not an integer or float
*/
public static function createFromNumber($number, int $precision = -1): Amount
{
if (!is_int($number) && !is_float($number)) {
throw new InvalidArgumentException(
"createFromNumber() expects an integer or float, found: " . gettype($number)
);
}
return new static(
number_format(
$number,
$precision >= 0 ? $precision : self::getInternalPrecision(),
'.',
''
)
);
}
/**
* Create amount from a formatted string
*/
public static function createFromFormat(string $amount, string $point = '.', string $sep = ''): Amount
{
return new static(
str_replace(
[$point, $sep, '[~placeholder~]'],
['[~placeholder~]', '', '.'],
$amount
)
);
}
/**
* Create amount from signal string
*
* Signal strings does not contain a decimal digit separator. Instead the
* last two digits are always considered decimals. For negative values the
* last digit is converted to an alphabetic character according to schema:
* 0 => å, 1 => J, 2 => K, ... 9 => R.
*
* @throws InvalidArgumentException If $signalStr is not a valid signal string
*/
public static function createFromSignalString(string $signalStr): Amount
{
if (!preg_match("/^\d+(å|[JKLMNOPQR])?$/", $signalStr)) {
throw new InvalidArgumentException("createFromSignalString() expects a valid signal string");
}
if (!is_numeric($signalStr)) {
$signalStr = '-' . str_replace(
self::$signals,
array_keys(self::$signals),
$signalStr
);
}
return new static(
preg_replace("/^(-?\d*)(\d\d)$/", "$1.$2", $signalStr, 1)
);
}
/**
* Get the raw stored amount
*/
public function getAmount(): string
{
return $this->amount;
}
/**
* Get new Amount rounded to $precision number of decimal digit using $rounder
*/
public function roundTo(int $precision = -1, Rounder $rounder = null): Amount
{
return new static(
($rounder ?: $this->getDefaultRounder())->round(
$this->getAmount(),
$precision >= 0 ? $precision : $this->getDisplayPrecision()
)
);
}
/**
* Get amount as string
*/
public function getString(int $precision = -1, Rounder $rounder = null): string
{
return bcadd(
$this->roundTo($precision, $rounder)->getAmount(),
'0.0',
$precision >= 0 ? $precision : $this->getDisplayPrecision()
);
}
/**
* Get amount as string
*/
public function __tostring(): string
{
return $this->getString();
}
/**
* Get amount as integer
*/
public function getInt(Rounder $rounder = null): int
{
return (int)$this->getFloat(0, $rounder);
}
/**
* Get amount as float
*
* It is important to note that computers internally use the binary floating
* point format and cannot accurately represent a number like 0.1, 0.2 or
* 0.3 at all. Using floating point numbers leads to a loss of precision.
* For example `floor((0.1+0.7)*10)` will usually return 7 instead of the
* expected 8, since the internal representation will be something like
* 7.9999999999999991118....
*
* For this reason floats should never ne used to store monetary data. This
* method exists for rare situations when converting to native formats is
* inevitable. Unless you know what you are doing it should NOT be used.
*/
public function getFloat(int $precision = -1, Rounder $rounder = null): float
{
return floatval($this->getString($precision, $rounder));
}
/**
* Get amount as signal string
*
* Signal strings does not contain a decimal digit separator. Instead the
* last two digits are always considered decimals. For negative values the
* last digit is converted to an alphabetic character according to schema:
* 0 => å, 1 => J, 2 => K, ... 9 => R.
*/
public function getSignalString(Rounder $rounder = null): string
{
if ($this->isNegative()) {
$signalStr = $this->getAbsolute()->getString(2, $rounder);
$signalStr = substr($signalStr, 0, -1) . self::$signals[substr($signalStr, -1)];
} else {
$signalStr = $this->getString(2, $rounder);
}
return str_replace('.', '', $signalStr);
}
/**
* Get new Amount with the value of $amount added to instance
*/
public function add(Amount $amount, int $precision = -1): Amount
{
return new static(
bcadd(
$this->getAmount(),
$amount->getAmount(),
$precision >= 0 ? $precision : $this->getInternalPrecision()
)
);
}
/**
* Get new Amount with the value of $amount subtracted from instance
*/
public function subtract(Amount $amount, int $precision = -1): Amount
{
return new static(
bcsub(
$this->getAmount(),
$amount->getAmount(),
$precision >= 0 ? $precision : $this->getInternalPrecision()
)
);
}
/**
* Get new Amount with the value of instance multiplied with $amount
*
* @param int|float|string|Amount $amount
*/
public function multiplyWith($amount, int $precision = -1): Amount
{
return new static(
bcmul(
$this->getAmount(),
$this->castToString($amount),
$precision >= 0 ? $precision : $this->getInternalPrecision()
)
);
}
/**
* Get new Amount with the value of instance divided by $amount
*
* @param int|float|string|Amount $divisor
*/
public function divideBy($divisor, int $precision = -1): Amount
{
$strDivisor = $this->castToString($divisor);
if (!bccomp($strDivisor, '0')) {
throw new DivisionByZeroException();
}
return new static(
bcdiv(
$this->getAmount(),
$strDivisor,
$precision >= 0 ? $precision : $this->getInternalPrecision()
)
);
}
/**
* Compare to amount
*
* @return int 0 if instance and $amount are equal, 1 if instance is larger, -1 otherwise.
*/
public function compareTo(Amount $amount, int $precision = -1): int
{
return bccomp(
$this->getAmount(),
$amount->getAmount(),
$precision >= 0 ? $precision : $this->getInternalPrecision()
);
}
/**
* Check if instance equals amount
*/
public function equals(Amount $amount, int $precision = -1): bool
{
return 0 == $this->compareTo($amount, $precision);
}
/**
* Check if instance is less than amount
*/
public function isLessThan(Amount $amount, int $precision = -1): bool
{
return -1 == $this->compareTo($amount, $precision);
}
/**
* Check if instance is less than or equals amount
*/
public function isLessThanOrEquals(Amount $amount, int $precision = -1): bool
{
return $this->isLessThan($amount, $precision) || $this->equals($amount, $precision);
}
/**
* Check if instance is greater than amount
*/
public function isGreaterThan(Amount $amount, int $precision = -1): bool
{
return 1 == $this->compareTo($amount, $precision);
}
/**
* Check if instance is greater than or equals amount
*/
public function isGreaterThanOrEquals(Amount $amount, int $precision = -1): bool
{
return $this->isGreaterThan($amount, $precision) || $this->equals($amount, $precision);
}
/**
* Check if amount is zero
*/
public function isZero(int $precision = -1): bool
{
return $this->equals(new static('0'), $precision);
}
/**
* Check if amount is greater than zero
*/
public function isPositive(int $precision = -1): bool
{
return $this->isGreaterThan(new static('0'), $precision);
}
/**
* Check if amount is less than zero
*/
public function isNegative(int $precision = -1): bool
{
return $this->isLessThan(new static('0'), $precision);
}
/**
* Get new Amount with sign inverted
*/
public function getInverted(): Amount
{
return $this->isNegative() ? $this->getAbsolute() : new static('-' . str_replace('+', '', $this->getAmount()));
}
/**
* Get new Amount with negative sign removed
*/
public function getAbsolute(): Amount
{
return new static(str_replace('-', '', $this->getAmount()));
}
/**
* Allocate amount based on a list of ratios
*
* @param int[]|float[] $ratios List of ratios
* @param int $precision Optional decimal precision used in calculation
* @return Amount[] The allocated amounts
*/
public function allocate(array $ratios, int $precision = -1): array
{
$remainder = clone $this;
$results = [];
$total = array_sum($ratios);
$precision = $precision >= 0 ? $precision : $this->getDisplayPrecision();
$unit = new static(bcdiv('1', '1' . str_repeat('0', $precision), $precision));
foreach ($ratios as $ratio) {
$share = $this->multiplyWith($ratio)->divideBy($total)->roundTo($precision, new Rounder\RoundDown);
$results[] = $share;
$remainder = $remainder->subtract($share);
}
for ($i = 0; $remainder->isGreaterThanOrEquals($unit) > 0; $i++) {
$results[$i] = $results[$i]->add($unit);
$remainder = $remainder->subtract($unit);
}
return $results;
}
/**
* Get the default display precision
*/
public static function getDisplayPrecision(): int
{
return 2;
}
/**
* Get the default internal precision used in computations
*/
public static function getInternalPrecision(): int
{
return 10;
}
/**
* Get default rounding strategy
*/
public static function getDefaultRounder(): Rounder
{
return new Rounder\RoundHalfUp;
}
/**
* Get a numerical string from input
*
* @param int|float|string|Amount $amount
* @throws InvalidArgumentException If $amount is does not evaluate to a numberical string
*/
private function castToString($amount): string
{
switch (gettype($amount)) {
case 'integer':
case 'double':
$amount = static::createFromNumber($amount);
break;
case 'string':
$amount = new static($amount);
break;
}
if (!$amount instanceof Amount) {
throw new InvalidArgumentException("Supplied argument is not valid");
}
return $amount->getAmount();
}
}