1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace MichaelRubel\StripeIntegration\Decorators; |
6
|
|
|
|
7
|
|
|
use Illuminate\Support\Str; |
8
|
|
|
use Money\Currency; |
9
|
|
|
use Money\Money; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* @method Currency getCurrency() |
13
|
|
|
*/ |
14
|
|
|
class StripePaymentAmount |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @var Money |
18
|
|
|
*/ |
19
|
|
|
public Money $money; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @param float $amount |
23
|
|
|
* @param string $currency |
24
|
|
|
* @param int $multiplier |
25
|
|
|
*/ |
26
|
13 |
|
public function __construct( |
27
|
|
|
public float $amount, |
28
|
|
|
public string $currency, |
29
|
|
|
public int $multiplier = 100 |
30
|
|
|
) { |
31
|
13 |
|
if ($this->multiplier === 0) { |
32
|
1 |
|
throw new \DivisionByZeroError('Zero is forbidden.'); |
33
|
|
|
} |
34
|
|
|
|
35
|
12 |
|
if (empty($this->currency)) { |
36
|
1 |
|
throw new \InvalidArgumentException('Currency code should not be empty.'); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
// Configures the payment amount decorator. |
40
|
|
|
// Used mainly for converting the amount |
41
|
|
|
// to payment-system friendly units. |
42
|
11 |
|
$this->money = new Money( |
43
|
11 |
|
amount: $this->toPaymentSystemUnits(), |
44
|
11 |
|
currency: new Currency( |
45
|
11 |
|
Str::upper($this->currency) |
46
|
11 |
|
) |
47
|
11 |
|
); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @return int |
52
|
|
|
*/ |
53
|
7 |
|
public function getAmount(): int |
54
|
|
|
{ |
55
|
7 |
|
return (int) $this->money->getAmount(); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* Convert to "smallest common currency units". |
60
|
|
|
* |
61
|
|
|
* @return int |
62
|
|
|
*/ |
63
|
11 |
|
public function toPaymentSystemUnits(): int |
64
|
|
|
{ |
65
|
11 |
|
return (int) ($this->amount * $this->multiplier); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* Revert from "smallest common currency units". |
70
|
|
|
* |
71
|
|
|
* @return float |
72
|
|
|
*/ |
73
|
1 |
|
public function fromPaymentSystemUnits(): float |
74
|
|
|
{ |
75
|
1 |
|
return $this->money->getAmount() / $this->multiplier; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* Forward call to the money object if the method doesn't exist in the decorator. |
80
|
|
|
* |
81
|
|
|
* @param string $method |
82
|
|
|
* @param array $parameters |
83
|
|
|
* @return mixed |
84
|
|
|
*/ |
85
|
5 |
|
public function __call(string $method, array $parameters): mixed |
86
|
|
|
{ |
87
|
5 |
|
return call($this->money)->{$method}(...$parameters); |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|