FlatRateBillInterpreter::interpret()   A
last analyzed

Complexity

Conditions 5
Paths 7

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 5
eloc 14
c 2
b 0
f 0
nc 7
nop 1
dl 0
loc 24
rs 9.4888
1
<?php
2
3
namespace BillingBoss\Interpreter;
4
5
use BillingBoss\Exception\RangeException;
6
use BillingBoss\Expr;
7
use BillingBoss\BillContext;
8
use BillingBoss\AbstractBillInterpreter;
9
use BillingBoss\RangeHelper;
10
use BillingBoss\Traits\RangeValidityCheck;
11
12
/**
13
 * Flat rate bill interpreter
14
 *
15
 * @package   BillingBoss
16
 * @link      https://github.com/ranskills/billing-boss-php
17
 * @copyright Copyright (c) 2018 Ransford Ako Okpoti
18
 * @license   Refer to the LICENSE distributed with this library
19
 * @since     1.0.0
20
 */
21
final class FlatRateBillInterpreter extends AbstractBillInterpreter
22
{
23
    use RangeValidityCheck;
24
25
    private const EXPRESSION = Expr::POSITIVE_NUMBER .
26
                               Expr::COMMA .
27
                               Expr::RANGE;
28
29
    public function __construct()
30
    {
31
        parent::__construct(sprintf('/^(%1$s)(%2$s%1$s)*$/', self::EXPRESSION, Expr::PIPE));
32
    }
33
34
    /**
35
     * @param BillContext $context
36
     * @return float
37
     * @throws RangeException
38
     */
39
    public function interpret(BillContext $context): float
40
    {
41
        if (!$this->isValid($context)) {
42
            return 0;
43
        }
44
        $bill = 0.0;
45
46
        $parts = preg_split(sprintf('/%s/', Expr::PIPE), $context->getStructure());
47
        $len = $parts === false ? 0 : count($parts);
48
49
        for ($i = 0; $i < $len; $i++) {
50
            $range = $this->ranges[$i];
51
            $matches = [];
52
53
            \preg_match(sprintf('/^%s$/', self::EXPRESSION), $parts[$i], $matches);
54
55
            $amount = $context->getAmount();
56
            if (RangeHelper::isInRange($range, $amount)) {
57
                $bill = $matches[1];
58
                break;
59
            }
60
        }
61
62
        return $bill;
63
    }
64
}
65