-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathEnumPrice.php
108 lines (92 loc) · 2.58 KB
/
EnumPrice.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?php
/**
* PHP Billing Library
*
* @link https://github.com/hiqdev/php-billing
* @package php-billing
* @license BSD-3-Clause
* @copyright Copyright (c) 2017-2020, HiQDev (http://hiqdev.com/)
*/
namespace hiqdev\php\billing\price;
use hiqdev\php\billing\plan\PlanInterface;
use hiqdev\php\billing\target\TargetInterface;
use hiqdev\php\billing\type\TypeInterface;
use hiqdev\php\units\QuantityInterface;
use hiqdev\php\units\UnitInterface;
use Money\Currency;
use Money\Money;
/**
* Enum Price:
* - holds sums list: amount => total sum for the quantity NOT price per unit
* - listed quantities only else exception.
* @see PriceInterface
*
* @author Andrii Vasyliev <[email protected]>
*/
class EnumPrice extends AbstractPrice implements PriceWithSumsInterface, PriceWithCurrencyInterface, PriceWithUnitInterface
{
protected UnitInterface $unit;
protected Currency $currency;
protected Sums $sums;
public function __construct(
$id,
TypeInterface $type,
TargetInterface $target,
?PlanInterface $plan,
UnitInterface $unit,
Currency $currency,
Sums $sums,
) {
parent::__construct($id, $type, $target, $plan);
$this->unit = $unit;
$this->currency = $currency;
$this->sums = $sums;
}
public function getUnit(): UnitInterface
{
return $this->unit;
}
public function getCurrency(): Currency
{
return $this->currency;
}
public function getSums(): Sums
{
return $this->sums;
}
/**
* {@inheritdoc}
*/
public function calculateSum(QuantityInterface $quantity): ?Money
{
$usage = $this->calculateUsage($quantity)->getQuantity();
foreach ($this->sums->values() as $value => $price) {
if ((string) $value === (string) $usage) {
return new Money($price, $this->currency);
}
}
throw new FailedCalculatePriceException('not enumed quantity: ' . $usage);
}
/**
* {@inheritdoc}
*/
public function calculatePrice(QuantityInterface $quantity): ?Money
{
$sum = $this->calculateSum($quantity);
if ($sum === null) {
return null;
}
$usage = $this->calculateUsage($quantity);
if ($usage === null) {
return null;
}
return $sum->divide(sprintf('%.14F', $usage->getQuantity()));
}
/**
* {@inheritdoc}
*/
public function calculateUsage(QuantityInterface $quantity): ?QuantityInterface
{
return $quantity->convert($this->unit);
}
}