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) |
|
|
|
|
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])); |
|
|
|
|
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
|
|
|
|
Adding explicit visibility (
private
,protected
, orpublic
) is generally recommend to communicate to other developers how, and from where this method is intended to be used.