Completed
Push — master ( cf838f...441ca2 )
by Dmitry
04:31
created

ServerHelper::getOsimages()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 6
ccs 0
cts 5
cp 0
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
crap 2
1
<?php
2
3
/*
4
 * Server module for HiPanel
5
 *
6
 * @link      https://github.com/hiqdev/hipanel-module-server
7
 * @package   hipanel-module-server
8
 * @license   BSD-3-Clause
9
 * @copyright Copyright (c) 2015-2016, HiQDev (http://hiqdev.com/)
10
 */
11
12
namespace hipanel\modules\server\helpers;
13
14
use hipanel\models\Ref;
15
use hipanel\modules\finance\models\Calculation;
16
use hipanel\modules\server\cart\Tariff;
17
use hipanel\modules\server\models\OpenvzPackage;
18
use hipanel\modules\server\models\Osimage;
19
use hipanel\modules\server\models\Package;
20
use hipanel\modules\server\models\ServerUse;
21
use hipanel\modules\stock\models\Part;
22
use hiqdev\hiart\ErrorResponseException;
23
use Yii;
24
use yii\helpers\ArrayHelper;
25
use yii\web\NotFoundHttpException;
26
use yii\web\UnprocessableEntityHttpException;
27
28
class ServerHelper
29
{
30
    public static function groupUsesForChart($uses)
31
    {
32
        $labels = [];
33
        $data = [];
34
35
        ArrayHelper::multisort($uses, 'date');
36
37
        foreach ($uses as $use) {
38
            /** @var ServerUse $use */
39
            $labels[$use->date] = $use;
0 ignored issues
show
Documentation introduced by
The property date does not exist on object<hipanel\modules\server\models\ServerUse>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
40
            $data[$use->type][] = $use->getDisplayAmount();
0 ignored issues
show
Documentation introduced by
The property type does not exist on object<hipanel\modules\server\models\ServerUse>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
41
        }
42
43
        foreach ($labels as $date => $use) {
44
            $labels[$date] = $use->getDisplayDate();
45
        }
46
47
        return [$labels, $data];
48
    }
49
50
    public static function getOsimages($type = null)
51
    {
52
        return Yii::$app->cache->getTimeCached(3600, [$type], function ($type) {
53
            return Osimage::find()->andFilterWhere(['type' => $type])->all();
54
        });
55
    }
56
57
    public static function groupOsmages($images, $ispSupported = false)
58
    {
59
        $softpacks = [];
60
        $oses = [];
61
        $vendors = [];
62
        foreach ($images as $image) {
63
            /** @var Osimage $image */
64
            $os = $image->os;
65
            $name = $image->getFullOsName();
66
            $panel = $image->getPanelName();
67
            $system = $image->getFullOsName('');
68
            $softpack_name = $image->getSoftPackName();
69
            $softpack = $image->getSoftPack();
70
71
            if (!array_key_exists($system, $oses)) {
72
                $vendors[$os]['name'] = $os;
73
                $vendors[$os]['oses'][$system] = $name;
74
                $oses[$system] = ['vendor' => $os, 'name' => $name];
75
            }
76
77
            if ($panel !== 'isp' || ($panel === 'isp' && $ispSupported)) {
78
                $data = [
79
                    'name' => $softpack_name,
80
                    'description' => preg_replace('/^ISPmanager - /', '', $softpack['description']),
81
                    'osimage' => $image->osimage,
82
                ];
83
84
                if ($softpack['soft']) {
85
                    $html_desc = [];
86
                    foreach ($softpack['soft'] as $soft => $soft_info) {
87
                        $soft_info['description'] = preg_replace('/,([^\s])/', ', $1', $soft_info['description']);
88
89
                        $html_desc[] = "<b>{$soft_info['name']} {$soft_info['version']}</b>: <i>{$soft_info['description']}</i>";
90
                        $data['soft'][$soft] = [
91
                            'name' => $soft_info['name'],
92
                            'version' => $soft_info['version'],
93
                            'description' => $soft_info['description'],
94
                        ];
95
                    }
96
                    $data['html_desc'] = implode('<br />', $html_desc);
97
                }
98
                $oses[$system]['panel'][$panel]['softpack'][$softpack_name] = $data;
99
                $softpacks[$panel][$softpack_name] = $data;
100
            } else {
101
                $oses[$system]['panel'][$panel] = false;
102
            }
103
        }
104
105
        foreach ($oses as $system => $os) {
106
            $delete = true;
107
            foreach ($os['panel'] as $panel => $info) {
108
                if ($info !== false) {
109
                    $delete = false;
110
                }
111
            }
112
            if ($delete) {
113
                unset($vendors[$os['vendor']]['oses'][$system]);
114
            }
115
        }
116
117
        return compact('vendors', 'oses', 'softpacks');
118
    }
119
120
    public static function getPanels()
121
    {
122
        return Ref::getList('type,panel');
123
    }
124
125
    /**
126
     * @param string $type (svds|ovds)
127
     * @param integer $tariff_id
128
     * @return Package|array
129
     * @throws NotFoundHttpException
130
     * @throws UnprocessableEntityHttpException
131
     */
132
    public static function getAvailablePackages($type = null, $tariff_id = null)
133
    {
134
        $part_ids = [];
135
        $parts = [];
136
        /** @var Calculation[] $calculations */
137
        $calculations = [];
138
139
        $cacheKeys = [
140
            Yii::$app->params['seller'],
141
            Yii::$app->user->id,
142
            $type,
143
            $tariff_id
144
        ];
145
146
        /** @var Tariff[] $tariffs */
147
        $tariffs = Yii::$app->getCache()->getTimeCached(3600, $cacheKeys, function ($seller, $client_id, $type, $tariff_id) {
148
            return Tariff::find(['scenario' => 'get-available-info'])
149
                ->joinWith('resources')
150
                ->where(['seller' => $seller])
151
                ->andFilterWhere(['id' => $tariff_id])
152
                ->andFilterWhere(['type' => $type])
153
                ->all();
154
        });
155
156
        foreach ($tariffs as $tariff) {
157
            $part_ids = ArrayHelper::merge($part_ids, array_filter(ArrayHelper::getColumn($tariff->resources, 'object_id')));
158
            $calculations[] = $tariff->getCalculationModel();
159
        }
160
161
        if (!empty($part_ids)) {
162
            $parts = Part::find()->where(['id' => $part_ids])->indexBy('id')->all();
163
        }
164
165
        $calculationData = [];
166
        foreach ((array)$calculations as $calculation) {
167
            $calculationData[$calculation->getPrimaryKey()] = $calculation->getAttributes();
168
        }
169
170
        try {
171
            $prices = Calculation::perform('CalcValue', $calculationData, true);
172
        } catch (ErrorResponseException $e) {
173
            $prices = $e->errorInfo['response'];
174
        } catch (\Exception $e) {
175
            throw new UnprocessableEntityHttpException('Failed to calculate tariff value', 0, $e);
176
        }
177
178
        $packages = [];
179
180
        foreach ($tariffs as $tariff) {
181
            $tariffParts = [];
182
            $tariffPartsIds = array_filter(ArrayHelper::getColumn($tariff->resources, 'object_id'));
183
184
            foreach ($parts as $id => $part) {
185
                if (in_array($id, $tariffPartsIds)) {
186
                    $tariffParts[$id] = $part;
187
                }
188
            }
189
190
            $packages[] = Yii::createObject([
191
                'class' => static::buildPackageClass($tariff),
192
                'tariff' => $tariff,
193
                'parts' => $tariffParts,
194
                'calculation' => $prices[$tariff->id],
195
            ]);
196
        }
197
198
        ArrayHelper::multisort($packages, 'price', SORT_ASC, SORT_NUMERIC);
199
200
        if (empty($packages)) {
201
            throw new NotFoundHttpException('Requested tariff is not available');
202
        }
203
204
        if (isset($tariff_id) && !is_array($tariff_id)) {
205
            return reset($packages);
206
        }
207
208
        return $packages;
209
    }
210
211
    public static function buildPackageClass($tariff)
212
    {
213
        if ($tariff->type === Tariff::TYPE_OPENVZ) {
214
            return OpenvzPackage::class;
215
        }
216
217
        return Package::class;
218
    }
219
}
220