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
|
|
|
* Percentage 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 PercentageBillInterpreter extends AbstractBillInterpreter |
22
|
|
|
{ |
23
|
|
|
use RangeValidityCheck; |
24
|
|
|
|
25
|
|
|
private const EXPRESSION = Expr::PERCENT . |
26
|
|
|
Expr::COMMA . |
27
|
|
|
Expr::RANGE; |
28
|
|
|
|
29
|
6 |
|
public function __construct() |
30
|
|
|
{ |
31
|
6 |
|
parent::__construct(sprintf('/^(%1$s)(%2$s%1$s)*$/', self::EXPRESSION, Expr::PIPE)); |
32
|
6 |
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @param BillContext $context |
36
|
|
|
* @return float |
37
|
|
|
* @throws RangeException |
38
|
|
|
*/ |
39
|
4 |
|
public function interpret(BillContext $context): float |
40
|
|
|
{ |
41
|
4 |
|
if (!$this->isValid($context)) { |
42
|
1 |
|
return 0.0; |
43
|
|
|
} |
44
|
3 |
|
$bill = 0.0; |
45
|
|
|
|
46
|
3 |
|
$parts = preg_split(sprintf('/%s/', Expr::PIPE), $context->getStructure()); |
47
|
3 |
|
$len = $parts === false ? 0 : count($parts); |
48
|
|
|
|
49
|
3 |
|
for ($i = 0; $i < $len; $i++) { |
50
|
3 |
|
$range = $this->ranges[$i]; |
51
|
3 |
|
$matches = []; |
52
|
|
|
|
53
|
3 |
|
\preg_match(sprintf('/^%s$/', self::EXPRESSION), $parts[$i], $matches); |
54
|
|
|
|
55
|
3 |
|
$amount = $context->getAmount(); |
56
|
|
|
|
57
|
3 |
|
if (RangeHelper::isInRange($range, $amount)) { |
58
|
3 |
|
$bill = ($matches[1] * $amount) / 100.00; |
59
|
3 |
|
break; |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
3 |
|
return $bill; |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|