Passed
Push — master ( 3fc31c...585ede )
by Dmitry
06:03
created

src/order/Calculator.php (2 issues)

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