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