Passed
Push — main ( 666372...550e71 )
by Michael
03:53
created

StripePaymentAmount::getAmount()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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