Completed
Push — master ( 8e3125...89e825 )
by Andrii
02:22
created

EnumPrice::calculateSum()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * PHP Billing Library
4
 *
5
 * @link      https://github.com/hiqdev/php-billing
6
 * @package   php-billing
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2017, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiqdev\php\billing\price;
12
13
use hiqdev\php\billing\target\TargetInterface;
14
use hiqdev\php\billing\type\TypeInterface;
15
use hiqdev\php\units\QuantityInterface;
16
use hiqdev\php\units\UnitInterface;
17
use Money\Currency;
18
use Money\Money;
19
20
/**
21
 * Enum Price:
22
 * - listed quantities only else exception.
23
 * @see PriceInterface
24
 *
25
 * @author Andrii Vasyliev <[email protected]>
26
 */
27
class EnumPrice extends AbstractPrice
28
{
29
    /**
30
     * @var UnitInterface
31
     */
32
    protected $unit;
33
34
    /**
35
     * @var Currency
36
     */
37
    protected $currency;
38
39
    /**
40
     * @var MoneyInterface[] amount => price
41
     */
42
    protected $prices;
43
44 2
    public function __construct(
45
                            $id,
46
        TypeInterface       $type,
47
        TargetInterface     $target,
48
        UnitInterface       $unit,
49
        Currency            $currency,
50
        array               $prices
51
    ) {
52 2
        parent::__construct($id, $type, $target);
53 2
        $this->unit = $unit;
54 2
        $this->currency = $currency;
55 2
        $this->prices = $prices;
56 2
    }
57
58 1
    public function getUnit()
59
    {
60 1
        return $this->unit;
61
    }
62
63 1
    public function getPrices()
64
    {
65 1
        return $this->prices;
66
    }
67
68
    /**
69
     * {@inheritdoc}
70
     */
71 2
    public function calculatePrice(QuantityInterface $quantity)
72
    {
73 2
        $usage = (string) $this->calculateUsage($quantity)->getQuantity();
74 2
        foreach ($this->prices as $value => $price) {
75 2
            if ((string) $value === (string) $usage) {
76 2
                return new Money($price, $this->currency);
77
            }
78
        }
79
80
        throw new FailedCalculatePriceException('not enumed quantity: ' . $usage);
81
    }
82
83
    /**
84
     * {@inheritdoc}
85
     */
86 2
    public function calculateUsage(QuantityInterface $quantity)
87
    {
88 2
        return $quantity->convert($this->unit);
89
    }
90
}
91