hiqdev /
php-billing
| 1 | <?php declare(strict_types=1); |
||
| 2 | |||
| 3 | namespace hiqdev\php\billing\price; |
||
| 4 | |||
| 5 | final readonly class Sums implements \JsonSerializable |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 6 | { |
||
| 7 | /** |
||
| 8 | * @param array<int, float|int>|null $quantityToSumMap An associative array where: |
||
| 9 | * - The key represents the **quantity** of the action being charged for |
||
| 10 | * (e.g., the number of years for an SSL certificate). |
||
| 11 | * - The value represents the **total sum** or **price** for the given quantity. |
||
| 12 | * |
||
| 13 | * Example (If used to denote bulk prices): |
||
| 14 | * E.g. when you buy an SSL certificate for 1 year – it costs 10$ |
||
| 15 | * But for 2 years you pay 15$. |
||
| 16 | * |
||
| 17 | * It will be is stored as |
||
| 18 | * |
||
| 19 | * [1 => 10, 2 => 15] |
||
| 20 | */ |
||
| 21 | public function __construct(private ?array $quantityToSumMap) |
||
| 22 | { |
||
| 23 | $this->validateSums($this->quantityToSumMap); |
||
| 24 | } |
||
| 25 | |||
| 26 | private function validateSums(?array $sums): void |
||
| 27 | { |
||
| 28 | if (!empty($sums)) { |
||
| 29 | foreach ($sums as $value) { |
||
| 30 | if (!is_numeric($value)) { |
||
| 31 | throw new PriceInvalidArgumentException('All sums must be numeric values.'); |
||
| 32 | } |
||
| 33 | } |
||
| 34 | } |
||
| 35 | } |
||
| 36 | |||
| 37 | public function values(): ?array |
||
| 38 | { |
||
| 39 | return $this->quantityToSumMap; |
||
| 40 | } |
||
| 41 | |||
| 42 | public function getSum(int $quantity) |
||
| 43 | { |
||
| 44 | return $this->quantityToSumMap[$quantity] ?? null; |
||
| 45 | } |
||
| 46 | |||
| 47 | public function getMinSum() |
||
| 48 | { |
||
| 49 | if (empty($this->quantityToSumMap)) { |
||
| 50 | return null; |
||
| 51 | } |
||
| 52 | |||
| 53 | return min($this->quantityToSumMap); |
||
| 54 | } |
||
| 55 | |||
| 56 | public function jsonSerialize(): ?array |
||
| 57 | { |
||
| 58 | return $this->quantityToSumMap; |
||
| 59 | } |
||
| 60 | } |
||
| 61 |