Completed
Push — master ( 95954c...739542 )
by Dmitry
17:54
created

ServerHelper   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 202
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 13

Test Coverage

Coverage 0%

Importance

Changes 9
Bugs 0 Features 2
Metric Value
wmc 27
c 9
b 0
f 2
lcom 0
cbo 13
dl 0
loc 202
ccs 0
cts 131
cp 0
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A groupUsesForChart() 0 19 3
A getOsimages() 0 6 1
C groupOsimages() 0 61 12
A getPanels() 0 4 1
B getAvailablePackages() 0 57 8
A buildPackageClass() 0 8 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
    /**
31
     * Method groups array of [[ServerUse]] in order to use it in charts.
32
     * @param ServerUse[] $uses
33
     * @return array of two items:
34
     *  0 - labels (like months)
35
     *  1 - values (value for each month)
36
     */
37
    public static function groupUsesForChart($uses)
38
    {
39
        $labels = [];
40
        $data = [];
41
42
        ArrayHelper::multisort($uses, 'date');
43
44
        foreach ($uses as $use) {
45
            /** @var ServerUse $use */
46
            $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...
47
            $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...
48
        }
49
50
        foreach ($labels as $date => $use) {
51
            $labels[$date] = $use->getDisplayDate();
52
        }
53
54
        return [$labels, $data];
55
    }
56
57
    /**
58
     * Gets array of [[Osimage]] for $type
59
     *
60
     * @param string $type
61
     * @return Osimage[]|null
62
     */
63
    public static function getOsimages($type = null)
64
    {
65
        return Yii::$app->cache->getTimeCached(3600, [$type], function ($type) {
66
            return Osimage::find()->andFilterWhere(['type' => $type])->all();
67
        });
68
    }
69
70
71
    /**
72
     * Regroups array of $images into 3 arrays of unique OS vendors (Ubuntu, FreeBSD, ...),
73
     * OSeses (Ubuntu 16.04, FreeBSD 10.3, ...) and softpacks (LAMP, no, ...)
74
     *
75
     * @param Osimage[] $images
76
     * @param bool $ispSupported whether ISP manager panel is supported
77
     * @return array of 3 elements:
78
     *  0 - vendors,
79
     *  1 - oses,
80
     *  2 - softpacks
81
     */
82
    public static function groupOsimages($images, $ispSupported = false)
83
    {
84
        $softpacks = [];
85
        $oses = [];
86
        $vendors = [];
87
        foreach ($images as $image) {
88
            $os = $image->os;
89
            $name = $image->getFullOsName();
90
            $panel = $image->getPanelName();
91
            $system = $image->getFullOsName('');
92
            $softpack_name = $image->getSoftPackName();
93
            $softpack = $image->getSoftPack();
94
95
            if (!array_key_exists($system, $oses)) {
96
                $vendors[$os]['name'] = $os;
97
                $vendors[$os]['oses'][$system] = $name;
98
                $oses[$system] = ['vendor' => $os, 'name' => $name];
99
            }
100
101
            if ($panel !== 'isp' || ($panel === 'isp' && $ispSupported)) {
102
                $data = [
103
                    'name' => $softpack_name,
104
                    'description' => preg_replace('/^ISPmanager - /', '', $softpack['description']),
105
                    'osimage' => $image->osimage,
106
                ];
107
108
                if ($softpack['soft']) {
109
                    $html_desc = [];
110
                    foreach ($softpack['soft'] as $soft => $soft_info) {
111
                        $soft_info['description'] = preg_replace('/,([^\s])/', ', $1', $soft_info['description']);
112
113
                        $html_desc[] = "<b>{$soft_info['name']} {$soft_info['version']}</b>: <i>{$soft_info['description']}</i>";
114
                        $data['soft'][$soft] = [
115
                            'name' => $soft_info['name'],
116
                            'version' => $soft_info['version'],
117
                            'description' => $soft_info['description'],
118
                        ];
119
                    }
120
                    $data['html_desc'] = implode('<br />', $html_desc);
121
                }
122
                $oses[$system]['panel'][$panel]['softpack'][$softpack_name] = $data;
123
                $softpacks[$panel][$softpack_name] = $data;
124
            } else {
125
                $oses[$system]['panel'][$panel] = false;
126
            }
127
        }
128
129
        foreach ($oses as $system => $os) {
130
            $delete = true;
131
            foreach ($os['panel'] as $panel => $info) {
132
                if ($info !== false) {
133
                    $delete = false;
134
                }
135
            }
136
            if ($delete) {
137
                unset($vendors[$os['vendor']]['oses'][$system]);
138
            }
139
        }
140
141
        return compact('vendors', 'oses', 'softpacks');
142
    }
143
144
    /**
145
     * @return array
146
     */
147
    public static function getPanels()
148
    {
149
        return Ref::getList('type,panel', 'hipanel/server/panel', []);
150
    }
151
152
    /**
153
     * @param string $type (svds|ovds)
154
     * @param integer $tariff_id
155
     * @throws NotFoundHttpException
156
     * @throws UnprocessableEntityHttpException
157
     * @return Package|array
158
     */
159
    public static function getAvailablePackages($type = null, $tariff_id = null)
160
    {
161
        $part_ids = [];
0 ignored issues
show
Unused Code introduced by
$part_ids is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
162
        $calculationData = [];
163
164
        $cacheKeys = [
165
            Yii::$app->params['seller'],
166
            Yii::$app->user->id,
167
            $type,
168
            $tariff_id,
169
        ];
170
171
        /** @var Tariff[] $tariffs */
172
        $tariffs = Yii::$app->getCache()->getTimeCached(2, $cacheKeys, function ($seller, $client_id, $type, $tariff_id) {
173
            return Tariff::find(['scenario' => 'get-available-info'])
174
                ->details()
175
                ->andWhere(['seller' => $seller])
176
                ->andFilterWhere(['id' => $tariff_id])
177
                ->andFilterWhere(['type' => $type])
178
                ->all();
179
        });
180
181
        foreach ($tariffs as $tariff) {
182
            $calculation = $tariff->getCalculationModel();
183
            $calculationData[$calculation->getPrimaryKey()] = $calculation->getAttributes();
184
        }
185
186
        try {
187
            $prices = Calculation::perform('CalcValue', $calculationData, true);
188
        } catch (ErrorResponseException $e) {
189
            $prices = $e->errorInfo['response'];
190
        } catch (\Exception $e) {
191
            throw new UnprocessableEntityHttpException('Failed to calculate tariff value', 0, $e);
192
        }
193
194
        $packages = [];
195
196
        foreach ($tariffs as $tariff) {
197
            $packages[] = Yii::createObject([
198
                'class' => static::buildPackageClass($tariff),
199
                'tariff' => $tariff,
200
                'calculation' => $prices[$tariff->id],
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<hipanel\modules\server\cart\Tariff>. 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...
201
            ]);
202
        }
203
204
        ArrayHelper::multisort($packages, 'price', SORT_ASC, SORT_NUMERIC);
205
206
        if (empty($packages)) {
207
            throw new NotFoundHttpException('Requested tariff is not available');
208
        }
209
210
        if (isset($tariff_id) && !is_array($tariff_id)) {
211
            return reset($packages);
212
        }
213
214
        return $packages;
215
    }
216
217
    /**
218
     * @param $tariff
219
     * @return mixed
220
     */
221
    public static function buildPackageClass($tariff)
222
    {
223
        if ($tariff->type === Tariff::TYPE_OPENVZ) {
224
            return OpenvzPackage::class;
225
        }
226
227
        return Package::class;
228
    }
229
}
230