Completed
Push — master ( 154e2e...1851c4 )
by Klochok
37:11 queued 22:06
created

ServerController   D

Complexity

Total Complexity 37

Size/Duplication

Total Lines 562
Duplicated Lines 8.9 %

Coupling/Cohesion

Components 0
Dependencies 22

Test Coverage

Coverage 0%

Importance

Changes 7
Bugs 0 Features 0
Metric Value
wmc 37
c 7
b 0
f 0
lcom 0
cbo 22
dl 50
loc 562
rs 4.9789
ccs 0
cts 174
cp 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A behaviors() 0 20 1
D actions() 37 412 17
C getVNCInfo() 0 25 7
A actionDrawChart() 0 22 3
A getOsimages() 0 16 3
A getOsimagesLiveCd() 0 12 2
A getPanelTypes() 0 4 1
A actionIsOperable() 0 12 2
A getFullFromRef() 13 13 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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-2017, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hipanel\modules\server\controllers;
12
13
use hipanel\actions\Action;
14
use hipanel\actions\ComboSearchAction;
15
use hipanel\actions\IndexAction;
16
use hipanel\actions\OrientationAction;
17
use hipanel\actions\PrepareBulkAction;
18
use hipanel\actions\ProxyAction;
19
use hipanel\actions\RedirectAction;
20
use hipanel\actions\RenderAction;
21
use hipanel\actions\RenderJsonAction;
22
use hipanel\actions\RequestStateAction;
23
use hipanel\actions\SmartDeleteAction;
24
use hipanel\actions\SmartPerformAction;
25
use hipanel\actions\SmartUpdateAction;
26
use hipanel\actions\ValidateFormAction;
27
use hipanel\actions\ViewAction;
28
use hipanel\base\CrudController;
29
use hipanel\models\Ref;
30
use hipanel\modules\finance\models\Tariff;
31
use hipanel\modules\server\cart\ServerRenewProduct;
32
use hipanel\modules\server\helpers\ServerHelper;
33
use hipanel\modules\server\models\Osimage;
34
use hipanel\modules\server\models\Server;
35
use hipanel\modules\server\models\ServerUseSearch;
36
use hiqdev\hiart\ResponseErrorException;
37
use hiqdev\yii2\cart\actions\AddToCartAction;
38
use Yii;
39
use yii\base\Event;
40
use yii\filters\VerbFilter;
41
use yii\helpers\ArrayHelper;
42
use yii\rest\UpdateAction;
43
use yii\web\NotFoundHttpException;
44
use yii\web\Response;
45
46
class ServerController extends CrudController
47
{
48
    public function behaviors()
49
    {
50
        return array_merge(parent::behaviors(), [
0 ignored issues
show
Bug Best Practice introduced by
The return type of return array_merge(paren...' => array('post'))))); (array<*,array>) is incompatible with the return type of the parent method hipanel\base\Controller::behaviors of type array[].

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
51
            'server-actions-verb' => [
52
                'class' => VerbFilter::class,
53
                'actions' => [
54
                    'reboot' => ['post'],
55
                    'reset' => ['post'],
56
                    'shutdown' => ['post'],
57
                    'power-off' => ['post'],
58
                    'power-on' => ['post'],
59
                    'reset-password' => ['post'],
60
                    'enable-block' => ['post'],
61
                    'disable-block' => ['post'],
62
                    'refuse' => ['post'],
63
                    'bulk-flush-switch-graphs' => ['post']
64
                ],
65
            ],
66
        ]);
67
    }
68
69
    public function actions()
70
    {
71
        return [
72
            'index' => [
73
                'class' => IndexAction::class,
74
                'findOptions' => ['with_requests' => true, 'with_discounts' => true],
75
                'on beforePerform' => function (Event $event) {
76
                    /** @var \hipanel\actions\SearchAction $action */
77
                    $action = $event->sender;
78
                    $dataProvider = $action->getDataProvider();
79
                    $dataProvider->query->joinWith(['ips', 'bindings']);
80
81
                    $dataProvider->query
82
                        ->andWhere(['with_ips' => 1])
83
                        ->andWhere(['with_tariffs' => 1])
84
                        ->andWhere(['with_requests' => 1])
85
                        ->andWhere(['with_discounts' => 1])
86
                        ->andWhere(['with_bindings' => 1])
87
                        ->select(['*']);
88
                },
89
                'filterStorageMap' => [
90
                    'name_like' => 'server.server.name',
91
                    'ips' => 'hosting.ip.ip_in',
92
                    'state' => 'server.server.state',
93
                    'client_id' => 'client.client.id',
94
                    'seller_id' => 'client.client.seller_id',
95
                ],
96
            ],
97
            'search' => [
98
                'class' => ComboSearchAction::class,
99
            ],
100
            'hardware-settings' => [
101
                'class' => SmartUpdateAction::class,
102
                'success' => Yii::t('hipanel:server:hub', 'Hardware properties was changed'),
103
                'view' => 'hardwareSettings',
104
            ],
105
            'software-settings' => [
106
                'class' => SmartUpdateAction::class,
107
                'success' => Yii::t('hipanel:server:hub', 'Software properties was changed'),
108
                'view' => 'softwareSettings',
109
            ],
110
            'monitoring-settings' => [
111
                'class' => SmartUpdateAction::class,
112
                'success' => Yii::t('hipanel:server:hub', 'Monitoring properties was changed'),
113
                'view' => 'monitoringSettings',
114 View Code Duplication
                'on beforeFetch' => function (Event $event) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
115
                    /** @var \hipanel\actions\SearchAction $action */
116
                    $action = $event->sender;
117
                    $dataProvider = $action->getDataProvider();
118
                    $dataProvider->query->joinWith(['monitoringSettings']);
119
                    $dataProvider->query
120
                        ->andWhere(['with_monitoringSettings' => 1])
121
                        ->select(['*']);
122
                },
123
                'data' => function ($action) {
124
                    return [
125
                        'nicMediaOptions' => $action->controller->getFullFromRef('type,nic_media'),
126
                    ];
127
                }
128
            ],
129
            'view' => [
130
                'class' => ViewAction::class,
131
                'on beforePerform' => function (Event $event) {
132
                    /** @var \hipanel\actions\SearchAction $action */
133
                    $action = $event->sender;
134
                    $dataProvider = $action->getDataProvider();
135
                    $dataProvider->query->joinWith(['uses', 'ips', 'switches', 'bindings']);
136
137
                    // TODO: ipModule is not wise yet. Redo
138
                    $dataProvider->query
139
                        ->andWhere(['with_requests' => 1])
140
                        ->andWhere(['show_deleted' => 1])
141
                        ->andWhere(['with_discounts' => 1])
142
                        ->andWhere(['with_uses' => 1])
143
                        ->andWhere(['with_ips' => 1])
144
                        ->andWhere(['with_bindings' => 1])
145
                        ->select(['*']);
146
                },
147
                'data' => function ($action) {
148
                    /**
149
                     * @var Action $action
150
                     * @var self $controller
151
                     * @var Server $model
152
                     */
153
                    $controller = $action->controller;
154
                    $model = $action->getModel();
155
                    $model->vnc = $controller->getVNCInfo($model);
0 ignored issues
show
Documentation Bug introduced by
The method getVNCInfo does not exist on object<hipanel\modules\s...trollers\HubController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
156
157
                    $panels = $controller->getPanelTypes();
0 ignored issues
show
Documentation Bug introduced by
The method getPanelTypes does not exist on object<hipanel\modules\s...trollers\HubController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
158
159
                    $cacheKeys = [__METHOD__, 'view', 'tariff', $model->tariff_id, Yii::$app->user->getId()];
160
                    $tariff = Yii::$app->cache->getOrSet($cacheKeys, function () use ($model) {
161
                        return Tariff::find()->where([
162
                            'id' => $model->tariff_id,
163
                            'show_final' => true,
164
                            'show_deleted' => true,
165
                            'with_resources' => true,
166
                        ])->joinWith('resources')->one();
167
                    });
168
169
                    $ispSupported = false;
170
                    if ($tariff !== null) {
171
                        foreach ($tariff->getResources() as $resource) {
172
                            if ($resource->type === 'isp' && $resource->quantity > 0) {
173
                                $ispSupported = true;
174
                            }
175
                        }
176
                    }
177
178
                    $osimages = $controller->getOsimages($model);
0 ignored issues
show
Documentation Bug introduced by
The method getOsimages does not exist on object<hipanel\modules\s...trollers\HubController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
179
                    $groupedOsimages = ServerHelper::groupOsimages($osimages, $ispSupported);
180
181
                    if ($model->isLiveCDSupported()) {
182
                        $osimageslivecd = $controller->getOsimagesLiveCd();
0 ignored issues
show
Documentation Bug introduced by
The method getOsimagesLiveCd does not exist on object<hipanel\modules\s...trollers\HubController>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
183
                    }
184
185
                    $blockReasons = $controller->getBlockReasons();
186
187
                    return compact([
188
                        'model',
189
                        'osimages',
190
                        'osimageslivecd',
191
                        'groupedOsimages',
192
                        'panels',
193
                        'blockReasons',
194
                    ]);
195
                },
196
            ],
197
            'requests-state' => [
198
                'class' => RequestStateAction::class,
199
                'model' => Server::class,
200
            ],
201
            'set-note' => [
202
                'class' => SmartUpdateAction::class,
203
                'view' => '_bulkSetNote',
204
                'success' => Yii::t('hipanel:server', 'Note changed'),
205
                'error' => Yii::t('hipanel:server', 'Failed to change note'),
206
            ],
207
            'set-label' => [
208
                'class' => SmartUpdateAction::class,
209
                'view' => '_bulkSetLabel',
210
                'success' => Yii::t('hipanel:server', 'Internal note changed'),
211
                'error' => Yii::t('hipanel:server', 'Failed to change internal note'),
212
            ],
213
            'set-lock' => [
214
                'class' => RenderAction::class,
215
                'success' => Yii::t('hipanel:server', 'Record was changed'),
216
                'error' => Yii::t('hipanel:server', 'Error occurred'),
217
                'POST pjax' => [
218
                    'save' => true,
219
                    'success' => [
220
                        'class' => ProxyAction::class,
221
                        'action' => 'index',
222
                    ],
223
                ],
224
                'POST' => [
225
                    'save' => true,
226
                    'success' => [
227
                        'class' => RenderJsonAction::class,
228
                        'return' => function ($action) {
229
                            /** @var \hipanel\actions\Action $action */
230
                            return $action->collection->models;
231
                        },
232
                    ],
233
                ],
234
            ],
235
            'sale' => [
236
                'class' => SmartUpdateAction::class,
237
                'view' => '_saleModal',
238
            ],
239
            'enable-vnc' => [
240
                'class' => ViewAction::class,
241
                'view' => '_vnc',
242
                'data' => function ($action) {
243
                    $model = $action->getModel();
244
                    if ($model->canEnableVNC()) {
245
                        $model->vnc = $this->getVNCInfo($model, true);
246
                    }
247
248
                    return [];
249
                },
250
            ],
251
            'bulk-sale' => [
252
                'class' => SmartUpdateAction::class,
253
                'scenario' => 'sale',
254
                'view' => '_bulkSale',
255
                'success' => Yii::t('hipanel:server', 'Servers were sold'),
256
                'POST pjax' => [
257
                    'save' => true,
258
                    'success' => [
259
                        'class' => ProxyAction::class,
260
                        'action' => 'index',
261
                    ],
262
                ],
263
                'on beforeSave' => function (Event $event) {
264
                    /** @var \hipanel\actions\Action $action */
265
                    $action = $event->sender;
266
                    $request = Yii::$app->request;
267
268
                    if ($client_id = $request->post('client_id')) {
269
                        foreach ($action->collection->models as $model) {
270
                            $model->client_id = $client_id;
271
                            if ($tariff_id = $request->post('tariff_id')) {
272
                                $model->tariff_id = $tariff_id;
273
                            }
274
                            if ($sale_time = $request->post('sale_time')) {
275
                                $model->sale_time = $sale_time;
276
                            }
277
                        }
278
                    }
279
                },
280
            ],
281
            'set-type' => [
282
                'class' => SmartUpdateAction::class,
283
                'view' => '_bulkSetType',
284
                'success' => Yii::t('hipanel:server', 'Type was changed'),
285
                'error' => Yii::t('hipanel:server', 'Failed to change type'),
286
            ],
287
            'reboot' => [
288
                'class' => SmartPerformAction::class,
289
                'success' => Yii::t('hipanel:server', 'Reboot task has been successfully added to queue'),
290
                'error' => Yii::t('hipanel:server', 'Error during the rebooting'),
291
            ],
292
            'reset' => [
293
                'class' => SmartPerformAction::class,
294
                'success' => Yii::t('hipanel:server', 'Reset task has been successfully added to queue'),
295
                'error' => Yii::t('hipanel:server', 'Error during the resetting'),
296
            ],
297
            'shutdown' => [
298
                'class' => SmartPerformAction::class,
299
                'success' => Yii::t('hipanel:server', 'Shutdown task has been successfully added to queue'),
300
                'error' => Yii::t('hipanel:server', 'Error during the shutting down'),
301
            ],
302
            'power-off' => [
303
                'class' => SmartPerformAction::class,
304
                'success' => Yii::t('hipanel:server', 'Power off task has been successfully added to queue'),
305
                'error' => Yii::t('hipanel:server', 'Error during the turning power off'),
306
            ],
307
            'power-on' => [
308
                'class' => SmartPerformAction::class,
309
                'success' => Yii::t('hipanel:server', 'Power on task has been successfully added to queue'),
310
                'error' => Yii::t('hipanel:server', 'Error during the turning power on'),
311
            ],
312
            'reset-password' => [
313
                'class' => SmartPerformAction::class,
314
                'success' => Yii::t('hipanel:server', 'Root password reset task has been successfully added to queue'),
315
                'error' => Yii::t('hipanel:server', 'Error during the resetting root password'),
316
            ],
317
            'enable-block' => [
318
                'class' => SmartPerformAction::class,
319
                'success' => Yii::t('hipanel:server', 'Server was blocked successfully'),
320
                'error' => Yii::t('hipanel:server', 'Error during the server blocking'),
321
            ],
322
            'disable-block' => [
323
                'class' => SmartPerformAction::class,
324
                'success' => Yii::t('hipanel:server', 'Server was unblocked successfully'),
325
                'error' => Yii::t('hipanel:server', 'Error during the server unblocking'),
326
            ],
327
            'refuse' => [
328
                'class' => SmartPerformAction::class,
329
                'success' => Yii::t('hipanel:server', 'You have refused the service'),
330
                'error' => Yii::t('hipanel:server', 'Error during the refusing the service'),
331
            ],
332
            'enable-autorenewal' => [
333
                'class' => SmartUpdateAction::class,
334
                'success' => Yii::t('hipanel:server', 'Server renewal enabled successfully'),
335
                'error' => Yii::t('hipanel:server', 'Error during the renewing the service'),
336
            ],
337
            'reinstall' => [
338
                'class' => SmartUpdateAction::class,
339
                'on beforeSave' => function (Event $event) {
340
                    /** @var Action $action */
341
                    $action = $event->sender;
342
                    foreach ($action->collection->models as $model) {
343
                        $model->osimage = Yii::$app->request->post('osimage');
344
                        $model->panel = Yii::$app->request->post('panel');
345
                    }
346
                },
347
                'success' => Yii::t('hipanel:server', 'Server reinstalling task has been successfully added to queue'),
348
                'error' => Yii::t('hipanel:server', 'Error during the server reinstalling'),
349
            ],
350
            'boot-live' => [
351
                'class' => SmartPerformAction::class,
352
                'on beforeSave' => function (Event $event) {
353
                    /** @var Action $action */
354
                    $action = $event->sender;
355
                    foreach ($action->collection->models as $model) {
356
                        $model->osimage = Yii::$app->request->post('osimage');
357
                    }
358
                },
359
                'success' => Yii::t('hipanel:server', 'Live CD booting task has been successfully added to queue'),
360
                'error' => Yii::t('hipanel:server', 'Error during the booting live CD'),
361
            ],
362
            'validate-form' => [
363
                'class' => ValidateFormAction::class,
364
            ],
365
            'buy' => [
366
                'class' => RedirectAction::class,
367
                'url' => Yii::$app->params['orgUrl'],
368
            ],
369
            'add-to-cart-renewal' => [
370
                'class' => AddToCartAction::class,
371
                'productClass' => ServerRenewProduct::class,
372
            ],
373
            'delete' => [
374
                'class' => SmartDeleteAction::class,
375
                'success' => Yii::t('hipanel:server', 'Server was deleted successfully'),
376
                'error' => Yii::t('hipanel:server', 'Failed to delete server'),
377
            ],
378
            'bulk-delete' => [
379
                'class' => SmartDeleteAction::class,
380
                'success' => Yii::t('hipanel:server', 'Server was deleted successfully'),
381
                'error' => Yii::t('hipanel:server', 'Failed to delete server'),
382
            ],
383
            'bulk-delete-modal' => [
384
                'class' => PrepareBulkAction::class,
385
                'view' => '_bulkDelete',
386
            ],
387
            'bulk-enable-block' => [
388
                'class' => SmartUpdateAction::class,
389
                'scenario' => 'enable-block',
390
                'success' => Yii::t('hipanel:server', 'Servers were blocked successfully'),
391
                'error' => Yii::t('hipanel:server', 'Error during the servers blocking'),
392
                'POST html' => [
393
                    'save' => true,
394
                    'success' => [
395
                        'class' => RedirectAction::class,
396
                    ],
397
                ],
398 View Code Duplication
                'on beforeSave' => function (Event $event) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
399
                    /** @var \hipanel\actions\Action $action */
400
                    $action = $event->sender;
401
                    $type = Yii::$app->request->post('type');
402
                    $comment = Yii::$app->request->post('comment');
403
                    if (!empty($type)) {
404
                        foreach ($action->collection->models as $model) {
405
                            $model->setAttributes([
406
                                'type' => $type,
407
                                'comment' => $comment,
408
                            ]);
409
                        }
410
                    }
411
                },
412
            ],
413
            'bulk-enable-block-modal' => [
414
                'class' => PrepareBulkAction::class,
415
                'view' => '_bulkEnableBlock',
416
                'data' => function ($action, $data) {
417
                    return array_merge($data, [
418
                        'blockReasons' => $this->getBlockReasons(),
419
                    ]);
420
                },
421
            ],
422
            'bulk-disable-block' => [
423
                'class' => SmartUpdateAction::class,
424
                'scenario' => 'disable-block',
425
                'success' => Yii::t('hipanel:server', 'Servers were unblocked successfully'),
426
                'error' => Yii::t('hipanel:server', 'Error during the servers unblocking'),
427
                'POST html' => [
428
                    'save' => true,
429
                    'success' => [
430
                        'class' => RedirectAction::class,
431
                    ],
432
                ],
433 View Code Duplication
                'on beforeSave' => function (Event $event) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
434
                    /** @var \hipanel\actions\Action $action */
435
                    $action = $event->sender;
436
                    $type = Yii::$app->request->post('type');
437
                    $comment = Yii::$app->request->post('comment');
438
                    if (!empty($type)) {
439
                        foreach ($action->collection->models as $model) {
440
                            $model->setAttributes([
441
                                'comment' => $comment,
442
                                'type' => $type
443
                            ]);
444
                        }
445
                    }
446
                },
447
            ],
448
            'bulk-disable-block-modal' => [
449
                'class' => PrepareBulkAction::class,
450
                'view' => '_bulkDisableBlock',
451
                'data' => function ($action, $data) {
452
                    return array_merge($data, [
453
                        'blockReasons' => $this->getBlockReasons()
454
                    ]);
455
                },
456
            ],
457
            'bulk-clear-resources' => [
458
                'class' => SmartPerformAction::class,
459
                'scenario' => 'clear-resources',
460
                'view' => '_clearResources',
461
                'success' => Yii::t('hipanel:server', 'Servers resources were cleared successfully'),
462
                'error' => Yii::t('hipanel:server', 'Error occurred during server resources flushing'),
463
            ],
464
            'clear-resources-modal' => [
465
                'class' => PrepareBulkAction::class,
466
                'view' => '_bulkClearResources',
467
            ],
468
            'bulk-flush-switch-graphs' => [
469
                'class' => SmartPerformAction::class,
470
                'scenario' => 'flush-switch-graphs',
471
                'view' => '_clearResources',
472
                'success' => Yii::t('hipanel:server', 'Switch graphs were flushed successfully'),
473
                'error' => Yii::t('hipanel:server', 'Error occurred during switch graphs flushing'),
474
            ],
475
            'flush-switch-graphs-modal' => [
476
                'class' => PrepareBulkAction::class,
477
                'view' => '_bulkFlushSwitchGraphs',
478
            ],
479
        ];
480
    }
481
482
    /**
483
     * Gets info of VNC on the server.
484
     *
485
     * @param Server $model
486
     * @param bool $enable
487
     * @throws ResponseErrorException
488
     * @return array
489
     */
490
    public function getVNCInfo($model, $enable = false)
491
    {
492
        if ($enable) {
493
            try {
494
                $vnc = Server::perform('enable-VNC', ['id' => $model->id]);
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<hipanel\modules\server\models\Server>. 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...
495
                $vnc['endTime'] = time() + 28800;
496
                Yii::$app->cache->set([__METHOD__, $model->id, $model], $vnc, 28800);
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<hipanel\modules\server\models\Server>. 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...
497
                $vnc['enabled'] = true;
498
            } catch (ResponseErrorException $e) {
499
                if ($e->getMessage() !== 'vds_has_tasks') {
500
                    throw $e;
501
                }
502
            }
503
        } else {
504
            if ($model->statuses['serverEnableVNC'] !== null && strtotime('+8 hours', strtotime($model->statuses['serverEnableVNC'])) > time()) {
0 ignored issues
show
Documentation introduced by
The property statuses does not exist on object<hipanel\modules\server\models\Server>. 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...
505
                $vnc = Yii::$app->cache->getOrSet([__METHOD__, $model->id, $model], function () use ($model) {
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<hipanel\modules\server\models\Server>. 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...
506
                    return ArrayHelper::merge([
507
                        'endTime' => strtotime($model->statuses['serverEnableVNC']) + 28800,
0 ignored issues
show
Documentation introduced by
The property statuses does not exist on object<hipanel\modules\server\models\Server>. 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...
508
                    ], Server::perform('enable-VNC', ['id' => $model->id]));
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<hipanel\modules\server\models\Server>. 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...
509
                }, 28800);
510
            }
511
            $vnc['enabled'] = $model->statuses['serverEnableVNC'] === null ? false : strtotime('+8 hours', strtotime($model->statuses['serverEnableVNC'])) > time();
0 ignored issues
show
Documentation introduced by
The property statuses does not exist on object<hipanel\modules\server\models\Server>. 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...
Bug introduced by
The variable $vnc does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
512
        }
513
        return $vnc;
514
    }
515
516
    public function actionDrawChart()
517
    {
518
        $post = Yii::$app->request->post();
519
        if (!in_array($post['type'], ['traffic', 'bandwidth'], true)) {
520
            throw new NotFoundHttpException();
521
        }
522
523
        $searchModel = new ServerUseSearch();
524
        $dataProvider = $searchModel->search([]);
525
        $dataProvider->pagination = false;
526
        $dataProvider->query->action('get-uses');
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface yii\db\QueryInterface as the method action() does only exist in the following implementations of said interface: hipanel\modules\client\models\query\ArticleQuery, hipanel\modules\client\models\query\ClientQuery, hipanel\modules\client\models\query\ContactQuery, hipanel\modules\finance\models\query\TariffQuery, hiqdev\hiart\ActiveQuery, hiqdev\hiart\Query.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
527
        $dataProvider->query->andWhere($post);
528
        $models = $dataProvider->getModels();
529
530
        list($labels, $data) = ServerHelper::groupUsesForChart($models);
0 ignored issues
show
Documentation introduced by
$models is of type array|null, but the function expects a array<integer,object<hip...rver\models\ServerUse>>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
531
532
        return $this->renderAjax('_consumption', [
533
            'labels' => $labels,
534
            'data' => $data,
535
            'consumptionBase' => $post['type'] === 'traffic' ? 'server_traf' : 'server_traf95',
536
        ]);
537
    }
538
539
    /**
540
     * Gets OS images.
541
     *
542
     * @param Server $model
543
     * @throws NotFoundHttpException
544
     * @return array
545
     */
546
    protected function getOsimages(Server $model = null)
547
    {
548
        if ($model !== null) {
549
            $type = $model->type;
0 ignored issues
show
Documentation introduced by
The property type does not exist on object<hipanel\modules\server\models\Server>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
550
        } else {
551
            $type = null;
552
        }
553
554
        $models = ServerHelper::getOsimages($type);
555
556
        if ($models === null) {
557
            throw new NotFoundHttpException('The requested page does not exist.');
558
        }
559
560
        return $models;
561
    }
562
563
    protected function getOsimagesLiveCd()
564
    {
565
        $models = Yii::$app->cache->getOrSet([__METHOD__], function () {
566
            return Osimage::findAll(['livecd' => true]);
567
        }, 3600);
568
569
        if ($models !== null) {
570
            return $models;
571
        }
572
573
        throw new NotFoundHttpException('The requested page does not exist.');
574
    }
575
576
    protected function getPanelTypes()
577
    {
578
        return ServerHelper::getPanels();
579
    }
580
581
    public function actionIsOperable($id)
582
    {
583
        Yii::$app->response->format = Response::FORMAT_JSON;
584
585
        $result = ['id' => $id, 'result' => false];
586
587
        if ($server = Server::find()->where(['id' => $id])->one()) {
588
            $result['result'] = $server->isOperable();
589
        }
590
591
        return $result;
592
    }
593
594 View Code Duplication
    protected function getFullFromRef($gtype)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
595
    {
596
        $callingMethod = debug_backtrace()[1]['function'];
597
        $result = Yii::$app->get('cache')->getOrSet([$callingMethod], function () use ($gtype) {
598
            $result = ArrayHelper::map(Ref::find()->where(['gtype' => $gtype, 'select' => 'full'])->all(), 'id', function ($model) {
599
                return Yii::t('hipanel:server:hub', $model->label);
600
            });
601
602
            return $result;
603
        }, 86400 * 24); // 24 days
604
605
        return $result;
606
    }
607
}
608