1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* AdvancedHosters implementation of HiPanel |
4
|
|
|
* |
5
|
|
|
* @link https://advancedhosters.com/ |
6
|
|
|
* @package hipanel |
7
|
|
|
* @license proprietary |
8
|
|
|
* @copyright Copyright (c) 2015-2017, AdvancedHosters (https://advancedhosters.com/) |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace advancedhosters\hipanel\cart; |
12
|
|
|
|
13
|
|
|
use hipanel\modules\finance\cart\Calculation; |
14
|
|
|
use hipanel\modules\finance\logic\ServerTariffCalculatorInterface; |
15
|
|
|
use hipanel\modules\finance\models\Tariff; |
16
|
|
|
use yii\base\InvalidParamException; |
17
|
|
|
use yii\base\NotSupportedException; |
18
|
|
|
|
19
|
|
|
class ServerTariffCalculator implements ServerTariffCalculatorInterface |
20
|
|
|
{ |
21
|
|
|
protected $tariffs; |
22
|
|
|
|
23
|
|
|
public function __construct($tariffs) |
24
|
|
|
{ |
25
|
|
|
$this->tariffs = $tariffs; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Calculates price for the model with $id |
30
|
|
|
* |
31
|
|
|
* @param $id |
32
|
|
|
* |
33
|
|
|
* @return Calculation |
34
|
|
|
*/ |
35
|
|
|
public function getCalculation($id) |
36
|
|
|
{ |
37
|
|
|
return $this->createCalculationFromTariff($this->getTariffById($id)); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @param Tariff $tariff |
42
|
|
|
* @return \hipanel\modules\finance\models\Calculation |
43
|
|
|
*/ |
44
|
|
|
private function createCalculationFromTariff($tariff) |
45
|
|
|
{ |
46
|
|
|
$value = floatval($tariff->getResourceByType('monthly')->price); |
47
|
|
|
|
48
|
|
|
$query = Calculation::find()->joinWith(['value'])->indexBy('calculation_id'); |
49
|
|
|
$query->prepare(); |
50
|
|
|
|
51
|
|
|
$data = [ |
52
|
|
|
'object' => $tariff->name, |
53
|
|
|
'currency' => $tariff->currency, |
54
|
|
|
'value' => [ |
55
|
|
|
$tariff->currency => [ |
56
|
|
|
'currency' => $tariff->currency, |
57
|
|
|
'value' => $value, |
58
|
|
|
'price' => $value, |
59
|
|
|
'discounted_price' => $value, |
60
|
|
|
] |
61
|
|
|
] |
62
|
|
|
]; |
63
|
|
|
|
64
|
|
|
return reset($query->populate([$data])); |
|
|
|
|
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
private function getTariffById($id) |
68
|
|
|
{ |
69
|
|
|
foreach ($this->tariffs as $tariff) { |
70
|
|
|
if (strcmp($tariff->id, $id) === 0) { |
71
|
|
|
return $tariff; |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
throw new InvalidParamException('Tariff with id "' . $id . '" does not exist in calculator'); |
|
|
|
|
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* Returns calculations for all passed models |
80
|
|
|
* |
81
|
|
|
* @return Calculation[] |
82
|
|
|
*/ |
83
|
|
|
public function getCalculations() |
84
|
|
|
{ |
85
|
|
|
$result = []; |
86
|
|
|
foreach ($this->tariffs as $tariff) { |
87
|
|
|
$result[] = $this->createCalculationFromTariff($tariff); |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
return $result; |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|