Completed
Push — master ( 6ed56d...9a6247 )
by Andrii
03:57
created

Calculator::findPlans()   B

Complexity

Conditions 8
Paths 12

Size

Total Lines 36
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 12.096

Importance

Changes 0
Metric Value
cc 8
eloc 22
nc 12
nop 1
dl 0
loc 36
ccs 12
cts 20
cp 0.6
crap 12.096
rs 8.4444
c 0
b 0
f 0
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-2018, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiqdev\php\billing\order;
12
13
use hiqdev\php\billing\action\ActionInterface;
14
use hiqdev\php\billing\charge\Charge;
15
use hiqdev\php\billing\charge\ChargeInterface;
16
use hiqdev\php\billing\charge\ChargeModifier;
17
use hiqdev\php\billing\charge\GeneralizerInterface;
18
use hiqdev\php\billing\plan\Plan;
19
use hiqdev\php\billing\plan\PlanInterface;
20
use hiqdev\php\billing\plan\PlanRepositoryInterface;
21
use hiqdev\php\billing\price\PriceInterface;
22
use hiqdev\php\billing\sale\Sale;
23
use hiqdev\php\billing\sale\SaleInterface;
24
use hiqdev\php\billing\sale\SaleRepositoryInterface;
25
use hiqdev\php\billing\type\TypeInterface;
26
27
/**
28
 * Calculator calculates charges for given order or action.
29
 *
30
 * @author Andrii Vasyliev <[email protected]>
31
 */
32
class Calculator implements CalculatorInterface
33
{
34
    /**
35
     * @var SaleRepositoryInterface
36
     */
37
    private $saleRepository;
38
39
    /**
40
     * @var PlanRepositoryInterface
41
     */
42
    private $planRepository;
43
44
    /**
45
     * @param SaleRepositoryInterface|null $saleRepository
46
     * @param PlanRepositoryInterface $planRepository
47
     * @throws \Exception
48 33
     */
49
    public function __construct(
50
        GeneralizerInterface $generalizer,
51
        ?SaleRepositoryInterface $saleRepository,
52
        ?PlanRepositoryInterface $planRepository
53 33
    ) {
54 33
        $this->generalizer    = $generalizer;
0 ignored issues
show
Bug Best Practice introduced by
The property generalizer does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
55 33
        $this->saleRepository = $saleRepository;
56 33
        $this->planRepository = $planRepository;
57
    }
58
59
    /**
60
     * {@inheritdoc}
61 2
     */
62
    public function calculateOrder(OrderInterface $order): array
63 2
    {
64 2
        $plans = $this->findPlans($order);
65 2
        $charges = [];
66 2
        foreach ($order->getActions() as $actionKey => $action) {
67
            if (empty($plans[$actionKey])) {
68
                /* XXX not sure... think more
69
                throw new FailedFindPlan();
70
                 */
71
                continue;
72
            }
73 2
74
            $charges[$actionKey] = $this->calculatePlan($plans[$actionKey], $action);
75
        }
76 2
77
        return $charges;
78
    }
79 4
80
    public function calculatePlan(PlanInterface $plan, ActionInterface $action): array
81 4
    {
82 4
        $result = [];
83 4
        foreach ($plan->getPrices() as $price) {
0 ignored issues
show
Bug introduced by
The method getPrices() does not exist on hiqdev\php\billing\plan\PlanInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to hiqdev\php\billing\plan\PlanInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

83
        foreach ($plan->/** @scrutinizer ignore-call */ getPrices() as $price) {
Loading history...
84 4
            $charges = $this->calculatePrice($price, $action);
85 4
            if (!empty($charges)) {
86
                $result = array_merge($result, $charges);
87
            }
88
        }
89 4
90
        return $result;
91
    }
92 4
93
    public function calculatePrice(PriceInterface $price, ActionInterface $action): array
94 4
    {
95 4
        $charge = $this->calculateCharge($price, $action);
96 4
        if ($charge === null) {
97
            return [];
98
        }
99 4
100 4
        $charges = [$charge];
101
        if ($price instanceof ChargeModifier) {
102
            $charges = $price->modifyCharge($charge, $action);
103
        }
104 4
105
        if ($action->isFinished()) {
106
            foreach ($charges as $charge) {
107
                $charge->setFinished();
108
            }
109
        }
110 4
111
        return $charges;
112
    }
113
114
    /**
115
     * Calculates charge for given action and price.
116
     * Returns `null`, if $price is not applicable to $action.
117
     *
118
     * @param PriceInterface $price
119
     * @param ActionInterface $action
120
     * @return ChargeInterface|Charge|null
121 25
     */
122
    public function calculateCharge(PriceInterface $price, ActionInterface $action): ?ChargeInterface
123 25
    {
124 8
        if (!$action->isApplicable($price)) {
125
            return null;
126
        }
127 21
128 21
        $usage = $price->calculateUsage($action->getQuantity());
129 4
        if ($usage === null) {
130
            return null;
131
        }
132 17
133 17
        $sum = $price->calculateSum($action->getQuantity());
134
        if ($sum === null) {
135
            return null;
136
        }
137 17
138 17
        $type = $this->generalizer->specializeType($price->getType(), $action->getType());
139
        $target = $this->generalizer->specializeTarget($price->getTarget(), $action->getTarget());
140
141
        /* sorry, debugging facility
142
         * var_dump([
143
            'unit'      => $usage->getUnit()->getName(),
144
            'quantity'  => $usage->getQuantity(),
145
            'price'     => $price->calculatePrice($usage)->getAmount(),
146
            'sum'       => $sum->getAmount(),
147
        ]);*/
148 17
149
        return new Charge(null, $type, $target, $action, $price, $usage, $sum);
150
    }
151
152
    /**
153
     * @param OrderInterface $order
154
     * @return PlanInterface[]|Plan
155
     * @throws \Exception
156 2
     */
157
    public function findPlans(OrderInterface $order)
158 2
    {
159 2
        $sales = $this->findSales($order);
160 2
        $plans = [];
161 2
        $lookPlanIds = [];
162 2
        foreach ($order->getActions() as $actionKey => $action) {
163
            if (empty($sales[$actionKey])) {
164
                /// it is ok when no sale found for upper resellers
165
                /// throw new \Exception('not found sale');
166
                $plans[$actionKey] = null;
167 2
            } else {
168
                $sale = $sales[$actionKey];
169 2
                /** @var Plan|PlanInterface[] $plan */
170 2
                $plan = $sale->getPlan();
171 2
                if ($plan->hasPrices()) {
172
                    $plans[$actionKey] = $plan;
173 2
                } else {
174
                    $lookPlanIds[$actionKey] = $plan->getId();
175
                }
176
            }
177
        }
178 2
179
        if ($lookPlanIds) {
180
            $foundPlans = $this->planRepository->findByIds($lookPlanIds);
181
            foreach ($foundPlans as $actionKey => $plan) {
182
                $foundPlans[$plan->getId()] = $plan;
183
            }
184
            foreach ($lookPlanIds as $actionKey => $planId) {
185
                if (empty($foundPlans[$planId])) {
186
                    throw new \Exception('not found plan');
187
                }
188
                $plans[$actionKey] = $foundPlans[$planId];
189
            }
190
        }
191 2
192
        return $plans;
193
    }
194
195
    /**
196
     * @param OrderInterface $order
197
     * @return SaleInterface[]|Sale
198 2
     */
199
    public function findSales(OrderInterface $order)
200 2
    {
201 2
        $sales = [];
202 2
        $lookActions = [];
203 2
        foreach ($order->getActions() as $actionKey => $action) {
204 2
            $sale = $action->getSale();
205
            if ($sale) {
206
                $sales[$actionKey] = $sale;
207 2
            } else {
208
                $lookActions[$actionKey] = $action;
209
            }
210
        }
211 2
212 2
        if ($lookActions) {
213 2
            $lookOrder = new Order(null, $order->getCustomer(), $lookActions);
214 2
            $foundSales = $this->saleRepository->findByOrder($lookOrder);
215 2
            foreach ($foundSales as $actionKey => $plan) {
216
                $sales[$actionKey] = $plan;
217
            }
218
        }
219 2
220
        return $sales;
221
    }
222
}
223