Passed
Push — master ( 9ee920...841385 )
by Kauri
52s
created

getPeriodInterestRate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
crap 1
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace Kauri\Loan\PaymentAmountCalculator;
6
7
use Kauri\Loan\PaymentAmountCalculator;
8
9
class EqualPrincipalPaymentAmountCalculator extends PaymentAmountCalculator
10
{
11
    /**
12
     * @param array $periods
13
     * @param float $presentValue
14
     * @param float $interestRate
15
     * @param float $futureValue
16
     * @return array
17
     */
18 4
    public function getPaymentAmounts(
19
        array $periods,
20
        float $presentValue,
21
        float $interestRate,
22
        float $futureValue
23
    ): array {
24 4
        $paymentAmounts = array();
25
26 4
        $principalLeft = $presentValue;
27 4
        $noOfPayments = count($periods);
28 4
        $principal = $this->getPrincipalPart($presentValue, $futureValue, $noOfPayments);
29
30 4
        foreach ($periods as $sequenceNo => $periodLength) {
31 4
            $ratePerPeriod = $this->interestAmountCalculator->getPeriodInterestRate($interestRate, $periodLength);
32 4
            $noOfRemainingPeriods = $noOfPayments - $sequenceNo + 1;
33
34 4
            $paymentAmount = $this->getPaymentAmount($principalLeft, $futureValue, $ratePerPeriod,
35
                $noOfRemainingPeriods);
36
37 4
            $principalLeft = $principalLeft - $principal;
38
39 4
            $paymentAmounts[$sequenceNo] = $paymentAmount;
40
        }
41
42 4
        return $paymentAmounts;
43
    }
44
45
    /**
46
     * @param float $presentValue
47
     * @param float $futureValue
48
     * @param int $noOfPeriods
49
     * @return float
50
     */
51 4
    private function getPrincipalPart(float $presentValue, float $futureValue, int $noOfPeriods): float
52
    {
53 4
        $principal = ($presentValue - $futureValue) / $noOfPeriods;
54
55 4
        return (float) $principal;
56
    }
57
58
    /**
59
     * @param float $presentValue
60
     * @param float $futureValue
61
     * @param float $ratePerPeriod
62
     * @param int $numberOfPeriods
63
     * @return float
64
     */
65 4
    private function getPaymentAmount(
66
        float $presentValue,
67
        float $futureValue,
68
        float $ratePerPeriod,
69
        int $numberOfPeriods
70
    ): float {
71 4
        $principal = $this->getPrincipalPart($presentValue, $futureValue, $numberOfPeriods);
72
73 4
        if ($ratePerPeriod > 0) {
74 1
            $payment = $principal + $presentValue * ($ratePerPeriod / 100);
75
        } else {
76 3
            $payment = $principal;
77
        }
78
79 4
        return (float) $payment;
80
    }
81
}
82