ProgressiveBillInterpreter::interpret()   A
last analyzed

Complexity

Conditions 5
Paths 3

Size

Total Lines 35
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 5
eloc 23
c 2
b 0
f 0
nc 3
nop 1
dl 0
loc 35
rs 9.2408
1
<?php
2
3
namespace BillingBoss\Interpreter;
4
5
use BillingBoss\BillContext;
6
use BillingBoss\AbstractBillInterpreter;
7
8
/**
9
 * Progressive bill interpreter
10
 *
11
 * @package   BillingBoss
12
 * @link      https://github.com/ranskills/billing-boss-php
13
 * @copyright Copyright (c) 2018 Ransford Ako Okpoti
14
 * @license   Refer to the LICENSE distributed with this library
15
 * @since     1.0.0
16
 */
17
final class ProgressiveBillInterpreter extends AbstractBillInterpreter
18
{
19
20
    public function __construct()
21
    {
22
        parent::__construct('/^(-?\d*\.?\d+)%,\s*(\d*\.?\d+)' .
23
        '(\s*>\s*(-?\d*\.?\d+)%,\s*(\d*\.?\d+))*(\s*>\s*(-?\d*\.?\d+)%,\s*(\*))$/');
24
    }
25
26
    public function interpret(BillContext $context): float
27
    {
28
        if (!$this->isValid($context)) {
29
            return 0.0;
30
        }
31
32
        $parts = preg_split('/\s*>\s*/', $context->getStructure());
33
        $billableAmount = $context->getAmount();
34
        $percentageBillInterpreter = new PercentageBillInterpreter();
35
        $percentageCtxt = new BillContext(0, '0%');
36
        $bill = 0;
37
38
        foreach ($parts as $part) {
39
            if ($billableAmount === 0.0) {
40
                break;
41
            }
42
            $matches = [];
43
44
            \preg_match('/^((-?\d*\.?\d+)%),\s*(\d*\.?\d+|\*)$/', $part, $matches);
45
            // print_r($matches);
46
            $amount = $matches[3];
47
            
48
            if ($amount === '*') {
49
                $percentageCtxt->setAmount(floatval($billableAmount))
50
                               ->setStructure($matches[1] . ', 1 - * ');
51
                $bill += $percentageBillInterpreter->interpret($percentageCtxt);
52
            } else {
53
                $billableAmount -= $amount;
54
                $percentageCtxt->setAmount($amount)
55
                               ->setStructure($matches[1] . ', 1 - * ');
56
                $bill += $percentageBillInterpreter->interpret($percentageCtxt);
57
            }
58
        }
59
60
        return $bill;
61
    }
62
}
63