Completed
Push — master ( 18bddc...22c7d7 )
by Klochok
09:09
created

Server::rules()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 71
Code Lines 55

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 55
c 1
b 0
f 0
dl 0
loc 71
ccs 2
cts 2
cp 1
rs 8.9818
cc 1
nc 1
nop 0
crap 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Server module for HiPanel
4
 *
5
 * @link      https://github.com/hiqdev/hipanel-module-server
6
 * @package   hipanel-module-server
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2015-2019, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hipanel\modules\server\models;
12
13
use hipanel\base\Model;
14
use hipanel\base\ModelTrait;
15
use hipanel\models\Ref;
16
use hipanel\modules\finance\models\Sale;
17
use hipanel\modules\hosting\models\Ip;
0 ignored issues
show
Bug introduced by
The type hipanel\modules\hosting\models\Ip was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
18
use hipanel\modules\server\helpers\ServerHelper;
19
use hipanel\modules\server\models\query\ServerQuery;
20
use hipanel\modules\server\models\traits\AssignSwitchTrait;
21
use hipanel\validators\EidValidator;
22
use hipanel\validators\RefValidator;
23
use Yii;
24
use yii\base\NotSupportedException;
25
26
/**
27
 * Class Server.
28
 *
29
 * @property int $id
30
 * @property string $name
31
 *
32
 * @property-read HardwareSale[] $hardwareSales
33
 */
34
class Server extends Model implements AssignSwitchInterface
35
{
36
    use ModelTrait, AssignSwitchTrait;
0 ignored issues
show
introduced by
The trait hipanel\modules\server\m...raits\AssignSwitchTrait requires some properties which are not provided by hipanel\modules\server\models\Server: $device_name, $typeWithNo, $bindings, $switch_name, $switch_id, $port, $type
Loading history...
37
38
    const STATE_OK = 'ok';
39
    const STATE_DISABLED = 'disabled';
40
    const STATE_BLOCKED = 'blocked';
41
    const STATE_DELETED = 'deleted';
42
43
    const VIRTUAL_DEVICES = ['avds', 'svds', 'ovds'];
44
45
    const SVDS_TYPES = ['avds', 'svds'];
46
47
    const DEFAULT_PANEL = 'rcp';
48
49 1
    public function rules()
50
    {
51
        return [
52 1
            [['show_last_sale'], 'boolean'],
53
            [['id', 'tariff_id', 'client_id', 'seller_id', 'mails_num'], 'integer'],
54
            [['osimage'], EidValidator::class],
55
            [['panel'], RefValidator::class],
56
            [
57
                [
58
                    'name', 'dc',
59
                    'client', 'seller',
60
                    'os', 'panel', 'rcp',
61
                    'parent_tariff', 'tariff', 'tariff_note', 'discounts',
62
                    'request_state', 'request_state_label',
63
                    'autorenewal',
64
                    'type', 'type_label', 'state', 'state_label', 'statuses',
65
                    'block_reason_label',
66
                    'running_task',
67
                    'ip', 'ips_num', 'mac',
68
                    'acs_num', 'del_acs_num', 'wizzarded',
69
                    'vnc',
70
                    'note', 'label', 'hwsummary', 'order_no',
71
                ],
72
                'safe',
73
            ],
74
            [['show_del', 'show_nic', 'show_vds', 'show_jail'], 'boolean'],
75
            [['switches', 'rack', 'net', 'kvm', 'pdu', 'ipmi'], 'safe'],
76
            [['last_expires', 'expires', 'status_time'], 'date'],
77
            [['time'], 'date', 'format' => 'php:Y-m-d H:i:s'],
78
            [
79
                ['state'],
80
                'isOperable',
81
                'on' => [
82
                    'reinstall',
83
                    'reboot',
84
                    'reset',
85
                    'shutdown',
86
                    'power-off',
87
                    'power-on',
88
                    'boot-live',
89
                    'regen-root-password',
90
                    'reset-password',
91
                ],
92
            ],
93
            [
94
                ['id'],
95
                'required',
96
                'on' => [
97
                    'refuse', 'delete', 'enable-autorenewal',
98
                    'enable-vnc', 'set-note', 'set-label',
99
                    'enable-block', 'disable-block', 'clear-resources',
100
                    'flush-switch-graphs',
101
                ],
102
            ],
103
            [
104
                ['id'],
105
                'integer',
106
                'on' => [
107
                    'refuse', 'delete', 'enable-autorenewal',
108
                    'enable-vnc', 'set-note', 'set-label',
109
                    'enable-block', 'disable-block',
110
                ],
111
            ],
112
            [['note'], 'string', 'max' => 50, 'on' => 'set-note'],
113
            [['id', 'osimage'], 'required', 'on' => ['reinstall']],
114
            [['id', 'osimage'], 'required', 'on' => ['boot-live']],
115
            [['type', 'comment'], 'required', 'on' => ['enable-block', 'disable-block']],
116
117
            [['tariff_id', 'sale_time'], 'required', 'on' => ['sale']],
118
            [['move_accounts'], 'safe', 'on' => ['sale']],
119
            [['id', 'type'], 'required', 'on' => ['set-type']],
120
        ];
121
    }
122
123
    /**
124
     * Determine good server states.
125
     *
126
     * @return array
127
     */
128
    public function goodStates()
129
    {
130
        return [static::STATE_OK, static::STATE_DISABLED];
131
    }
132
133
    /**
134
     * @return bool
135
     */
136
    public function isOperable()
137
    {
138
        if ($this->running_task || !$this->isStateGood()) {
0 ignored issues
show
Bug Best Practice introduced by
The property running_task does not exist on hipanel\modules\server\models\Server. Since you implemented __get, consider adding a @property annotation.
Loading history...
139
            return false;
140
        }
141
142
        return true;
143
    }
144
145
    public function canEnableVNC()
146
    {
147
        return $this->isVNCSupported() && $this->isStateGood();
148
    }
149
150
    public function isStateGood()
151
    {
152
        return in_array($this->state, $this->goodStates(), true);
0 ignored issues
show
Bug Best Practice introduced by
The property state does not exist on hipanel\modules\server\models\Server. Since you implemented __get, consider adding a @property annotation.
Loading history...
153
    }
154
155
    /**
156
     * Checks whether server supports VNC.
157
     *
158
     * @return bool
159
     */
160
    public function isVNCSupported()
161
    {
162
        return in_array($this->type, static::SVDS_TYPES, true);
0 ignored issues
show
Bug Best Practice introduced by
The property type does not exist on hipanel\modules\server\models\Server. Since you implemented __get, consider adding a @property annotation.
Loading history...
163
    }
164
165
    /**
166
     * Checks whether server supports root password change.
167
     *
168
     * @return bool
169
     */
170
    public function isPwChangeSupported()
171
    {
172
        return $this->type === 'ovds';
0 ignored issues
show
Bug Best Practice introduced by
The property type does not exist on hipanel\modules\server\models\Server. Since you implemented __get, consider adding a @property annotation.
Loading history...
173
    }
174
175
    /**
176
     * Checks whether server supports LiveCD.
177
     *
178
     * @return bool
179
     */
180
    public function isLiveCDSupported()
181
    {
182
        return in_array($this->type, static::SVDS_TYPES, true);
0 ignored issues
show
Bug Best Practice introduced by
The property type does not exist on hipanel\modules\server\models\Server. Since you implemented __get, consider adding a @property annotation.
Loading history...
183
    }
184
185
    /**
186
     * Check whether server is virtual.
187
     *
188
     * @return bool
189
     */
190
    public function isVirtualDevice()
191
    {
192
        return in_array($this->type, static::VIRTUAL_DEVICES, true);
0 ignored issues
show
Bug Best Practice introduced by
The property type does not exist on hipanel\modules\server\models\Server. Since you implemented __get, consider adding a @property annotation.
Loading history...
193
    }
194
195
    /**
196
     * Check whether server is dedicated.
197
     *
198
     * @return bool
199
     */
200
    public function isDedicatedDevice()
201
    {
202
        return $this->type === 'dedicated';
0 ignored issues
show
Bug Best Practice introduced by
The property type does not exist on hipanel\modules\server\models\Server. Since you implemented __get, consider adding a @property annotation.
Loading history...
203
    }
204
205
    public function getIsBlocked()
206
    {
207
        return $this->state === static::STATE_BLOCKED;
0 ignored issues
show
Bug Best Practice introduced by
The property state does not exist on hipanel\modules\server\models\Server. Since you implemented __get, consider adding a @property annotation.
Loading history...
208
    }
209
210
    /**
211
     * Checks whether server can be operated not.
212
     *
213
     * @throws NotSupportedException
214
     * @return bool
215
     * @see isOperable()
216
     */
217
    public function checkOperable()
218
    {
219
        if (!$this->isOperable()) {
220
            throw new NotSupportedException(Yii::t('hipanel:server', 'Server already has a running task. Can not start new.'));
221
        }
222
223
        return true;
224
    }
225
226
    /**
227
     * {@inheritdoc}
228
     */
229
    public function scenarioActions()
230
    {
231
        return [
232
            'reinstall' => 'resetup',
233
            'reset-password' => 'regen-root-password',
234
        ];
235
    }
236
237
    /**
238
     * During 5 days after the last expiration client is able to refuse server with full refund.
239
     * Method checks, whether 5 days passed.
240
     * @return bool
241
     */
242
    public function canFullRefuse()
243
    {
244
        if (!is_numeric($this->last_expires)) {
0 ignored issues
show
Bug Best Practice introduced by
The property last_expires does not exist on hipanel\modules\server\models\Server. Since you implemented __get, consider adding a @property annotation.
Loading history...
245
            return null; // In case server is not sold
246
        }
247
248
        return (time() - Yii::$app->formatter->asTimestamp($this->last_expires)) / 3600 / 24 < 5;
249
    }
250
251
    /**
252
     * @return bool
253
     */
254
    public function canRrd(): bool
255
    {
256
        return isset($this->ip) && isset($this->wizzarded);
0 ignored issues
show
Bug Best Practice introduced by
The property ip does not exist on hipanel\modules\server\models\Server. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug Best Practice introduced by
The property wizzarded does not exist on hipanel\modules\server\models\Server. Since you implemented __get, consider adding a @property annotation.
Loading history...
257
    }
258
259
    public function groupUsesForCharts()
260
    {
261
        return ServerHelper::groupUsesForChart($this->uses);
0 ignored issues
show
Bug Best Practice introduced by
The property uses does not exist on hipanel\modules\server\models\Server. Since you implemented __get, consider adding a @property annotation.
Loading history...
262
    }
263
264
    public function getUses()
265
    {
266
        return $this->hasMany(ServerUse::class, ['object_id' => 'id']);
267
    }
268
269
    public function getIps()
270
    {
271
        if (Yii::getAlias('@ip', false)) {
272
            return $this->hasMany(Ip::class, ['device_id' => 'id'])->joinWith('links');
273
        }
274
275
        return [];
276
    }
277
278
    public function getSwitches()
279
    {
280
        return $this->hasMany(Server::class, ['obj_id' => 'id']);
281
    }
282
283
    public function getConsumptions()
284
    {
285
        return $this->hasMany(Consumption::class, ['object_id' => 'id'])->indexBy('type');
286
    }
287
288
    public function getBindings()
289
    {
290
        return $this->hasMany(Binding::class, ['device_id' => 'id'])->indexBy(function ($binding) {
291
            return $binding->typeWithNo;
292
        });
293
    }
294
295
    public function getSales()
296
    {
297
        return $this->hasMany(Sale::class, ['id' => 'object_id']);
298
    }
299
300
    public function getMonitoringSettings()
301
    {
302
        return $this->hasOne(MonitoringSettings::class, ['id' => 'id']);
303
    }
304
305
    public function getHardwareSettings()
306
    {
307
        return $this->hasOne(HardwareSettings::class, ['id' => 'id']);
308
    }
309
310
    public function getHardwareSales()
311
    {
312
        return $this->hasMany(HardwareSale::class, ['id' => 'id']);
313
    }
314
315
    public function getSoftwareSettings()
316
    {
317
        return $this->hasOne(SoftwareSettings::class, ['id' => 'id']);
318
    }
319
320
    public function getMailSettings()
321
    {
322
        return $this->hasOne(MailSettings::class, ['id' => 'id']);
323
    }
324
325
    public function getBinding($type)
326
    {
327
        if (!isset($this->bindings[$type])) {
0 ignored issues
show
Bug Best Practice introduced by
The property bindings does not exist on hipanel\modules\server\models\Server. Since you implemented __get, consider adding a @property annotation.
Loading history...
328
            return null;
329
        }
330
331
        return $this->bindings[$type];
332
    }
333
334
    public function getPanel()
335
    {
336
        if ($this->state === self::STATE_DISABLED) {
0 ignored issues
show
Bug Best Practice introduced by
The property state does not exist on hipanel\modules\server\models\Server. Since you implemented __get, consider adding a @property annotation.
Loading history...
337
            return null;
338
        }
339
340
        if ($this->panel || $this->isVirtualDevice()) {
0 ignored issues
show
Bug Best Practice introduced by
The property panel does not exist on hipanel\modules\server\models\Server. Since you implemented __get, consider adding a @property annotation.
Loading history...
341
            return $this->panel;
342
        }
343
344
        return self::DEFAULT_PANEL;
345
    }
346
347
    /**
348
     * {@inheritdoc}
349
     */
350
    public function attributeLabels()
351
    {
352
        return $this->mergeAttributeLabels([
353
            'remoteid' => Yii::t('hipanel:server', 'Remote ID'),
354
            'name' => Yii::t('hipanel:server', 'Name'),
355
            'dc' => Yii::t('hipanel:server', 'DC'),
356
            'net' => Yii::t('hipanel:server', 'Switch'),
357
            'kvm' => Yii::t('hipanel:server', 'KVM'),
358
            'pdu' => Yii::t('hipanel:server', 'APC'),
359
            'rack' => Yii::t('hipanel:server', 'Rack'),
360
            'ipmi' => Yii::t('hipanel:server', 'IPMI'),
361
            'status_time' => Yii::t('hipanel:server', 'Status update time'),
362
            'block_reason_label' => Yii::t('hipanel:server', 'Block reason label'),
363
            'request_state_label' => Yii::t('hipanel:server', 'Request state label'),
364
            'mac' => Yii::t('hipanel:server', 'MAC'),
365
            'ips' => Yii::t('hipanel:server', 'IPs'),
366
            'label' => Yii::t('hipanel:server', 'Internal note'),
367
            'os' => Yii::t('hipanel:server', 'OS'),
368
            'comment' => Yii::t('hipanel:server', 'Comment'),
369
            'hwsummary' => Yii::t('hipanel:server', 'Hardware Summary'),
370
            'sale_time' => Yii::t('hipanel:server', 'Sale time'),
371
            'expires' => Yii::t('hipanel:server', 'Expires'),
372
            'tariff_id' => Yii::t('hipanel:server', 'Tariff'),
373
            'order_no' => Yii::t('hipanel:server', 'Order'),
374
            'move_accounts' => Yii::t('hipanel:server', 'Move accounts to new client'),
375
            'server' => Yii::t('hipanel:server', 'Server name'),
376
            'mails_num' => Yii::t('hipanel:server', 'Number of mailboxes'),
377
        ]);
378
    }
379
380
    public function getTypeOptions(): array
381
    {
382
        return Ref::getList('type,device,server', 'hipanel:server');
383
    }
384
385
    public function getStateOptions(): array
386
    {
387
        return [
388
            self::STATE_DISABLED    => Yii::t('hipanel:server', 'Ok, panel OFF'),
389
            self::STATE_OK          => Yii::t('hipanel:server', 'Ok'),
390
            self::STATE_BLOCKED     => Yii::t('hipanel:server', 'Blocked'),
391
        ];
392
    }
393
394
    /**
395
     * {@inheritdoc}
396
     * @return ServerQuery
397
     */
398
    public static function find($options = [])
399
    {
400
        return new ServerQuery(get_called_class(), [
401
            'options' => $options,
402
        ]);
403
    }
404
405
    /**
406
     * @return bool
407
     */
408
    public function canControlPower(): bool
409
    {
410
        $powerManagementAllowed = Yii::$app->params['module.server.power.management.allowed'];
411
412
        $userCanControlPower = Yii::$app->user->can('support') &&
0 ignored issues
show
Bug introduced by
The method can() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

412
        $userCanControlPower = Yii::$app->user->/** @scrutinizer ignore-call */ can('support') &&

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
413
            (Yii::$app->user->can('server.control-system') ||
414
            Yii::$app->user->can('server.control-power'));
415
416
        return $powerManagementAllowed || $userCanControlPower;
417
    }
418
}
419