Completed
Push — master ( 503dcd...d703ef )
by Dmitry
12:45
created

createCalculationFromTariff()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 22
rs 9.2
cc 1
eloc 14
nc 1
nop 1
1
<?php
2
3
namespace advancedhosters\hipanel\cart;
4
5
use hipanel\modules\finance\cart\Calculation;
6
use hipanel\modules\finance\logic\ServerTariffCalculatorInterface;
7
use hipanel\modules\finance\models\Tariff;
8
use yii\base\InvalidParamException;
9
10
class ServerTariffCalculator implements ServerTariffCalculatorInterface
11
{
12
    protected $tariffs;
13
14
    function __construct($tariffs)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
15
    {
16
        $this->tariffs = $tariffs;
17
    }
18
19
    /**
20
     * Calculates price for the model with $id
21
     *
22
     * @param $id
23
     *
24
     * @return Calculation
25
     */
26
    public function getCalculation($id)
27
    {
28
        return $this->createCalculationFromTariff($this->getTariffById($id));
29
    }
30
31
    /**
32
     * @param Tariff $tariff
33
     * @return \hipanel\modules\finance\models\Calculation
34
     */
35
    private function createCalculationFromTariff($tariff)
36
    {
37
        $value = $tariff->getResourceByType('monthly')->price;
38
39
        $query = Calculation::find()->joinWith(['value'])->indexBy('calculation_id');
40
        $query->prepare();
41
42
        $data = [
43
            'object' => $tariff->name,
44
            'currency' => $tariff->currency,
45
            'value' => [
46
                $tariff->currency => [
47
                    'currency' => $tariff->currency,
48
                    'value' => $value,
49
                    'price' => $value,
50
                    'discounted_price' => $value,
51
                ]
52
            ]
53
        ];
54
55
        return reset($query->populate([$data]));
0 ignored issues
show
Bug introduced by
$query->populate(array($data)) cannot be passed to reset() as the parameter $array expects a reference.
Loading history...
56
    }
57
58
    private function getTariffById($id)
59
    {
60
        foreach ($this->tariffs as $tariff) {
61
            if (strcmp($tariff->id, $id) === 0) {
62
                return $tariff;
63
            }
64
        }
65
66
        throw new InvalidParamException('Tariff with id "' . $id . '" does not exist in calculator');
67
    }
68
69
    /**
70
     * Returns calculations for all passed models
71
     *
72
     * @return Calculation[]
73
     */
74
    public function getCalculations()
75
    {
76
77
    }
78
}
79