Completed
Push — master ( d4d5bf...d1115f )
by Dmitry
13:18
created

ServerController::actions()   D

Complexity

Conditions 18
Paths 1

Size

Total Lines 466
Code Lines 327

Duplication

Lines 52
Ratio 11.16 %

Code Coverage

Tests 105
CRAP Score 64.2703

Importance

Changes 7
Bugs 0 Features 0
Metric Value
c 7
b 0
f 0
dl 52
loc 466
ccs 105
cts 220
cp 0.4773
rs 4.7996
cc 18
eloc 327
nc 1
nop 0
crap 64.2703

How to fix   Long Method    Complexity   

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-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\PrepareBulkAction;
17
use hipanel\actions\ProxyAction;
18
use hipanel\actions\RedirectAction;
19
use hipanel\actions\RenderAction;
20
use hipanel\actions\RenderJsonAction;
21
use hipanel\actions\RequestStateAction;
22
use hipanel\actions\SmartDeleteAction;
23
use hipanel\actions\SmartPerformAction;
24
use hipanel\actions\SmartUpdateAction;
25
use hipanel\actions\ValidateFormAction;
26
use hipanel\actions\ViewAction;
27
use hipanel\base\CrudController;
28
use hipanel\models\Ref;
29
use hipanel\modules\finance\models\Tariff;
30
use hipanel\modules\server\cart\ServerRenewProduct;
31
use hipanel\modules\server\helpers\ServerHelper;
32
use hipanel\modules\server\models\HardwareSettings;
33
use hipanel\modules\server\models\MonitoringSettings;
34
use hipanel\modules\server\models\Osimage;
35
use hipanel\modules\server\models\Server;
36
use hipanel\modules\server\models\ServerUseSearch;
37
use hipanel\modules\server\models\SoftwareSettings;
38
use hipanel\modules\server\widgets\ResourceConsumption;
39
use hipanel\modules\server\widgets\TrafficConsumption;
40
use hiqdev\hiart\ResponseErrorException;
41
use hiqdev\yii2\cart\actions\AddToCartAction;
42
use Yii;
43
use yii\base\Event;
44
use yii\filters\VerbFilter;
45
use yii\helpers\ArrayHelper;
46
use yii\web\NotFoundHttpException;
47
use yii\web\Response;
48
49
class ServerController extends CrudController
50
{
51
    public function behaviors()
52
    {
53
        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...
54
            'server-actions-verb' => [
55
                'class' => VerbFilter::class,
56
                'actions' => [
57
                    'reboot' => ['post'],
58
                    'reset' => ['post'],
59
                    'shutdown' => ['post'],
60
                    'power-off' => ['post'],
61
                    'power-on' => ['post'],
62
                    'reset-password' => ['post'],
63
                    'enable-block' => ['post'],
64
                    'disable-block' => ['post'],
65
                    'refuse' => ['post'],
66
                    'flush-switch-graphs' => ['post'],
67
                ],
68
            ],
69
        ]);
70
    }
71 1
72
    public function actions()
73 1
    {
74 1
        return array_merge(parent::actions(), [
75
            'index' => [
76
                'class' => IndexAction::class,
77 1
                'findOptions' => ['with_requests' => true, 'with_discounts' => true],
78
                'on beforePerform' => function (Event $event) {
79
                    /** @var \hipanel\actions\SearchAction $action */
80
                    $action = $event->sender;
81
                    $dataProvider = $action->getDataProvider();
82
                    $dataProvider->query->joinWith(['ips', 'bindings']);
83
84
                    $dataProvider->query
85
                        ->andWhere(['with_ips' => 1])
86
                        ->andWhere(['with_requests' => 1])
87
                        ->andWhere(['with_discounts' => 1])
88
                        ->andWhere(['with_bindings' => 1])
89 1
                        ->select(['*']);
90
                },
91
                'filterStorageMap' => [
92
                    'name_like' => 'server.server.name',
93
                    'ips' => 'hosting.ip.ip_in',
94
                    'state' => 'server.server.state',
95
                    'client_id' => 'client.client.id',
96
                    'seller_id' => 'client.client.seller_id',
97
                ],
98
            ],
99
            'search' => [
100
                'class' => ComboSearchAction::class,
101
            ],
102
            'hardware-settings' => [
103 1
                'class' => SmartUpdateAction::class,
104 1
                'success' => Yii::t('hipanel:server', 'Hardware properties was changed'),
105 1
                'view' => 'hardwareSettings',
106 1
                'scenario' => 'default',
107 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...
108
                    /** @var \hipanel\actions\SearchAction $action */
109
                    $action = $event->sender;
110
                    $dataProvider = $action->getDataProvider();
111
                    $dataProvider->query->joinWith(['hardwareSettings']);
112 1
                    $dataProvider->query->andWhere(['with_hardwareSettings' => 1])->select(['*']);
113 1
                },
114
                'on beforeLoad' => function (Event $event) {
115
                    /** @var Action $action */
116
                    $action = $event->sender;
117
118 1
                    $action->collection->setModel(HardwareSettings::class);
119
                },
120
                'POST html' => [
121
                    'save' => true,
122
                    'success' => [
123 1
                        'class' => RedirectAction::class,
124
                        'url' => function () {
125
                            $server = Yii::$app->request->post('HardwareSettings');
126
127 1
                            return ['@server/view', 'id' => $server['id']];
128
                        },
129
                    ],
130
                ],
131
            ],
132
            'software-settings' => [
133 1
                'class' => SmartUpdateAction::class,
134 1
                'success' => Yii::t('hipanel:server', 'Software properties was changed'),
135 1
                'view' => 'softwareSettings',
136 1
                'scenario' => 'default',
137 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...
138
                    /** @var \hipanel\actions\SearchAction $action */
139
                    $action = $event->sender;
140
                    $dataProvider = $action->getDataProvider();
141
                    $dataProvider->query->joinWith(['softwareSettings']);
142 1
                    $dataProvider->query->andWhere(['with_softwareSettings' => 1])->select(['*']);
143 1
                },
144
                'on beforeLoad' => function (Event $event) {
145
                    /** @var Action $action */
146
                    $action = $event->sender;
147
148 1
                    $action->collection->setModel(SoftwareSettings::class);
149
                },
150
                'POST html' => [
151
                    'save' => true,
152
                    'success' => [
153 1
                        'class' => RedirectAction::class,
154
                        'url' => function () {
155
                            $server = Yii::$app->request->post('SoftwareSettings');
156
157 1
                            return ['@server/view', 'id' => $server['id']];
158
                        },
159
                    ],
160
                ],
161
            ],
162
            'monitoring-settings' => [
163 1
                'class' => SmartUpdateAction::class,
164 1
                'success' => Yii::t('hipanel:server', 'Monitoring properties was changed'),
165 1
                'view' => 'monitoringSettings',
166 1
                'scenario' => 'default',
167 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...
168
                    /** @var \hipanel\actions\SearchAction $action */
169
                    $action = $event->sender;
170
                    $dataProvider = $action->getDataProvider();
171
                    $dataProvider->query->joinWith(['monitoringSettings']);
172
                    $dataProvider->query
173 1
                        ->andWhere(['with_monitoringSettings' => 1])->select(['*']);
174 1
                },
175
                'on beforeLoad' => function (Event $event) {
176
                    /** @var Action $action */
177
                    $action = $event->sender;
178
179 1
                    $action->collection->setModel(MonitoringSettings::class);
180 1
                },
181
                'data' => function ($action) {
182
                    return [
183
                        'nicMediaOptions' => $action->controller->getFullFromRef('type,nic_media'),
184 1
                    ];
185
                },
186
                'POST html' => [
187
                    'save' => true,
188
                    'success' => [
189 1
                        'class' => RedirectAction::class,
190
                        'url' => function () {
191
                            $server = Yii::$app->request->post('MonitoringSettings');
192
193 1
                            return ['@server/view', 'id' => $server['id']];
194
                        },
195
                    ],
196
                ],
197
            ],
198
            'view' => [
199 1
                'class' => ViewAction::class,
200
                'on beforePerform' => function (Event $event) {
201
                    /** @var \hipanel\actions\SearchAction $action */
202
                    $action = $event->sender;
203
                    $dataProvider = $action->getDataProvider();
204
                    $dataProvider->query->joinWith(['uses', 'ips', 'switches', 'bindings', 'blocking']);
205
206
                    // TODO: ipModule is not wise yet. Redo
207
                    $dataProvider->query
208
                        ->andWhere(['with_requests' => 1])
209
                        ->andWhere(['show_deleted' => 1])
210
                        ->andWhere(['with_discounts' => 1])
211
                        ->andWhere(['with_uses' => 1])
212
                        ->andWhere(['with_ips' => 1])
213
                        ->andWhere(['with_bindings' => 1])
214
                        ->andWhere(['with_blocking' => 1])
215 1
                        ->select(['*']);
216 1
                },
217
                'data' => function ($action) {
218
                    /**
219
                     * @var Action $action
220
                     * @var self $controller
221
                     * @var Server $model
222
                     */
223
                    $controller = $action->controller;
224
                    $model = $action->getModel();
225
                    $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...
226
227
                    $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...
228
229
                    $cacheKeys = [__METHOD__, 'view', 'tariff', $model->tariff_id, Yii::$app->user->getId()];
230
                    $tariff = Yii::$app->cache->getOrSet($cacheKeys, function () use ($model) {
231
                        return Tariff::find()->where([
232
                            'id' => $model->tariff_id,
233
                            'show_final' => true,
234
                            'show_deleted' => true,
235
                            'with_resources' => true,
236
                        ])->joinWith('resources')->one();
237
                    });
238
239
                    $ispSupported = false;
240
                    if ($tariff !== null) {
241
                        foreach ($tariff->getResources() as $resource) {
242
                            if ($resource->type === 'isp' && $resource->quantity > 0) {
243
                                $ispSupported = true;
244
                            }
245
                        }
246
                    }
247
248
                    $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...
249
                    $groupedOsimages = ServerHelper::groupOsimages($osimages, $ispSupported);
250
251
                    if ($model->isLiveCDSupported()) {
252
                        $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...
253
                    }
254
255
                    $blockReasons = $controller->getBlockReasons();
256
257
                    return compact([
258
                        'model',
259
                        'osimages',
260
                        'osimageslivecd',
261
                        'groupedOsimages',
262
                        'panels',
263
                        'blockReasons',
264 1
                    ]);
265
                },
266
            ],
267
            'requests-state' => [
268
                'class' => RequestStateAction::class,
269
                'model' => Server::class,
270
            ],
271
            'set-note' => [
272 1
                'class' => SmartUpdateAction::class,
273 1
                'view' => '_bulkSetNote',
274 1
                'success' => Yii::t('hipanel:server', 'Note changed'),
275
                'error' => Yii::t('hipanel:server', 'Failed to change note'),
276
            ],
277
            'set-label' => [
278 1
                'class' => SmartUpdateAction::class,
279 1
                'view' => '_bulkSetLabel',
280 1
                'success' => Yii::t('hipanel:server', 'Internal note changed'),
281
                'error' => Yii::t('hipanel:server', 'Failed to change internal note'),
282
            ],
283
            'set-lock' => [
284 1
                'class' => RenderAction::class,
285 1
                'success' => Yii::t('hipanel:server', 'Record was changed'),
286
                'error' => Yii::t('hipanel:server', 'Error occurred'),
287
                'POST pjax' => [
288
                    'save' => true,
289
                    'success' => [
290
                        'class' => ProxyAction::class,
291
                        'action' => 'index',
292
                    ],
293
                ],
294
                'POST' => [
295
                    'save' => true,
296
                    'success' => [
297 1
                        'class' => RenderJsonAction::class,
298
                        'return' => function ($action) {
299
                            /** @var \hipanel\actions\Action $action */
300 1
                            return $action->collection->models;
301
                        },
302
                    ],
303
                ],
304
            ],
305
            'sale' => [
306
                'class' => SmartUpdateAction::class,
307
                'view' => '_saleModal',
308
            ],
309
            'enable-vnc' => [
310 1
                'class' => ViewAction::class,
311 1
                'view' => '_vnc',
312
                'data' => function ($action) {
313
                    $model = $action->getModel();
314
                    if ($model->canEnableVNC()) {
315
                        $model->vnc = $this->getVNCInfo($model, true);
316
                    }
317
318 1
                    return [];
319
                },
320
            ],
321
            'bulk-sale' => [
322 1
                'class' => SmartUpdateAction::class,
323 1
                'scenario' => 'sale',
324 1
                'view' => '_bulkSale',
325
                'success' => Yii::t('hipanel:server', 'Servers were sold'),
326
                'POST pjax' => [
327
                    'save' => true,
328
                    'success' => [
329
                        'class' => ProxyAction::class,
330
                        'action' => 'index',
331
                    ],
332 1
                ],
333
                'on beforeSave' => function (Event $event) {
334
                    /** @var \hipanel\actions\Action $action */
335
                    $action = $event->sender;
336
                    $request = Yii::$app->request;
337
338
                    if ($client_id = $request->post('client_id')) {
339
                        $tariff_id = $request->post('tariff_id');
340
                        $sale_time = $request->post('sale_time');
341
                        $move_accounts = $request->post('move_accounts');
342
                        foreach ($action->collection->models as $model) {
343
                            $model->client_id = $client_id;
344
                            if ($tariff_id) {
345
                                $model->tariff_id = $tariff_id;
346
                            }
347
                            if ($sale_time) {
348
                                $model->sale_time = $sale_time;
349
                            }
350
                            if ($move_accounts) {
351
                                $model->move_accounts = $move_accounts;
352
                            }
353
                        }
354 1
                    }
355
                },
356
            ],
357
            'set-type' => [
358 1
                'class' => SmartUpdateAction::class,
359 1
                'view' => '_bulkSetType',
360 1
                'success' => Yii::t('hipanel:server', 'Type was changed'),
361
                'error' => Yii::t('hipanel:server', 'Failed to change type'),
362
            ],
363
            'reboot' => [
364 1
                'class' => SmartPerformAction::class,
365 1
                'success' => Yii::t('hipanel:server', 'Reboot task has been successfully added to queue'),
366
                'error' => Yii::t('hipanel:server', 'Error during the rebooting'),
367
            ],
368
            'reset' => [
369 1
                'class' => SmartPerformAction::class,
370 1
                'success' => Yii::t('hipanel:server', 'Reset task has been successfully added to queue'),
371
                'error' => Yii::t('hipanel:server', 'Error during the resetting'),
372
            ],
373
            'shutdown' => [
374 1
                'class' => SmartPerformAction::class,
375 1
                'success' => Yii::t('hipanel:server', 'Shutdown task has been successfully added to queue'),
376
                'error' => Yii::t('hipanel:server', 'Error during the shutting down'),
377
            ],
378
            'power-off' => [
379 1
                'class' => SmartPerformAction::class,
380 1
                'success' => Yii::t('hipanel:server', 'Power off task has been successfully added to queue'),
381
                'error' => Yii::t('hipanel:server', 'Error during the turning power off'),
382
            ],
383
            'power-on' => [
384 1
                'class' => SmartPerformAction::class,
385 1
                'success' => Yii::t('hipanel:server', 'Power on task has been successfully added to queue'),
386
                'error' => Yii::t('hipanel:server', 'Error during the turning power on'),
387
            ],
388
            'reset-password' => [
389 1
                'class' => SmartPerformAction::class,
390 1
                'success' => Yii::t('hipanel:server', 'Root password reset task has been successfully added to queue'),
391
                'error' => Yii::t('hipanel:server', 'Error during the resetting root password'),
392
            ],
393
            'enable-block' => [
394 1
                'class' => SmartPerformAction::class,
395 1
                'success' => Yii::t('hipanel:server', 'Server was blocked successfully'),
396
                'error' => Yii::t('hipanel:server', 'Error during the server blocking'),
397
                'POST html' => [
398
                    'save' => true,
399
                    'success' => [
400
                        'class' => RedirectAction::class,
401
                    ],
402 1
                ],
403 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...
404
                    /** @var \hipanel\actions\Action $action */
405
                    $action = $event->sender;
406
                    $type = Yii::$app->request->post('type');
407
                    $comment = Yii::$app->request->post('comment');
408
                    if (!empty($type)) {
409
                        foreach ($action->collection->models as $model) {
410
                            $model->setAttributes([
411
                                'type' => $type,
412
                                'comment' => $comment,
413
                            ]);
414
                        }
415 1
                    }
416
                },
417
            ],
418
            'bulk-enable-block-modal' => [
419 1
                'class' => PrepareBulkAction::class,
420 1
                'view' => '_bulkEnableBlock',
421
                'data' => function ($action, $data) {
422
                    return array_merge($data, [
423
                        'blockReasons' => $this->getBlockReasons(),
424 1
                    ]);
425
                },
426
            ],
427
            'disable-block' => [
428 1
                'class' => SmartPerformAction::class,
429 1
                'success' => Yii::t('hipanel:server', 'Server was unblocked successfully'),
430
                'error' => Yii::t('hipanel:server', 'Error during the server unblocking'),
431
                'POST html' => [
432
                    'save' => true,
433
                    'success' => [
434
                        'class' => RedirectAction::class,
435
                    ],
436 1
                ],
437 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...
438
                    /** @var \hipanel\actions\Action $action */
439
                    $action = $event->sender;
440
                    $type = Yii::$app->request->post('type');
441
                    $comment = Yii::$app->request->post('comment');
442
                    if (!empty($type)) {
443
                        foreach ($action->collection->models as $model) {
444
                            $model->setAttributes([
445
                                'comment' => $comment,
446
                                'type' => $type,
447
                            ]);
448
                        }
449 1
                    }
450
                },
451
            ],
452
            'bulk-disable-block-modal' => [
453 1
                'class' => PrepareBulkAction::class,
454 1
                'view' => '_bulkDisableBlock',
455
                'data' => function ($action, $data) {
456
                    return array_merge($data, [
457
                        'blockReasons' => $this->getBlockReasons(),
458 1
                    ]);
459
                },
460
            ],
461
            'refuse' => [
462 1
                'class' => SmartPerformAction::class,
463 1
                'success' => Yii::t('hipanel:server', 'You have refused the service'),
464
                'error' => Yii::t('hipanel:server', 'Error during the refusing the service'),
465
            ],
466
            'enable-autorenewal' => [
467 1
                'class' => SmartUpdateAction::class,
468 1
                'success' => Yii::t('hipanel:server', 'Server renewal enabled successfully'),
469
                'error' => Yii::t('hipanel:server', 'Error during the renewing the service'),
470
            ],
471
            'reinstall' => [
472 1
                'class' => SmartUpdateAction::class,
473
                'on beforeSave' => function (Event $event) {
474
                    /** @var Action $action */
475
                    $action = $event->sender;
476
                    foreach ($action->collection->models as $model) {
477
                        $model->osimage = Yii::$app->request->post('osimage');
478
                        $model->panel = Yii::$app->request->post('panel');
479 1
                    }
480 1
                },
481 1
                'success' => Yii::t('hipanel:server', 'Server reinstalling task has been successfully added to queue'),
482
                'error' => Yii::t('hipanel:server', 'Error during the server reinstalling'),
483
            ],
484
            'boot-live' => [
485 1
                'class' => SmartPerformAction::class,
486
                'on beforeSave' => function (Event $event) {
487
                    /** @var Action $action */
488
                    $action = $event->sender;
489
                    foreach ($action->collection->models as $model) {
490
                        $model->osimage = Yii::$app->request->post('osimage');
491 1
                    }
492 1
                },
493 1
                'success' => Yii::t('hipanel:server', 'Live CD booting task has been successfully added to queue'),
494
                'error' => Yii::t('hipanel:server', 'Error during the booting live CD'),
495
            ],
496
            'validate-form' => [
497
                'class' => ValidateFormAction::class,
498
            ],
499
            'buy' => [
500 1
                'class' => RedirectAction::class,
501
                'url' => Yii::$app->params['organization.url'],
502
            ],
503
            'add-to-cart-renewal' => [
504
                'class' => AddToCartAction::class,
505
                'productClass' => ServerRenewProduct::class,
506
            ],
507
            'delete' => [
508 1
                'class' => SmartDeleteAction::class,
509 1
                'success' => Yii::t('hipanel:server', 'Server was deleted successfully'),
510
                'error' => Yii::t('hipanel:server', 'Failed to delete server'),
511
            ],
512
            'bulk-delete-modal' => [
513
                'class' => PrepareBulkAction::class,
514
                'view' => '_bulkDelete',
515
            ],
516
            'clear-resources' => [
517 1
                'class' => SmartPerformAction::class,
518 1
                'view' => '_clearResources',
519 1
                'success' => Yii::t('hipanel:server', 'Servers resources were cleared successfully'),
520
                'error' => Yii::t('hipanel:server', 'Error occurred during server resources flushing'),
521
            ],
522
            'clear-resources-modal' => [
523
                'class' => PrepareBulkAction::class,
524
                'view' => '_clearResources',
525
            ],
526
            'flush-switch-graphs' => [
527 1
                'class' => SmartPerformAction::class,
528 1
                'view' => '_clearResources',
529 1
                'success' => Yii::t('hipanel:server', 'Switch graphs were flushed successfully'),
530
                'error' => Yii::t('hipanel:server', 'Error occurred during switch graphs flushing'),
531
            ],
532
            'flush-switch-graphs-modal' => [
533
                'class' => PrepareBulkAction::class,
534
                'view' => '_flushSwitchGraphs',
535
            ],
536
        ]);
537
    }
538
539
    /**
540
     * Gets info of VNC on the server.
541
     *
542
     * @param Server $model
543
     * @param bool $enable
544
     * @throws ResponseErrorException
545
     * @return array
546
     */
547
    public function getVNCInfo($model, $enable = false)
548
    {
549
        if ($enable) {
550
            try {
551
                $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...
552
                $vnc['endTime'] = time() + 28800;
553
                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...
554
                $vnc['enabled'] = true;
555
            } catch (ResponseErrorException $e) {
556
                if ($e->getMessage() !== 'vds_has_tasks') {
557
                    throw $e;
558
                }
559
            }
560
        } else {
561
            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...
562
                $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...
563
                    return ArrayHelper::merge([
564
                        '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...
565
                    ], 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...
566
                }, 28800);
567
            }
568
            $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...
569
        }
570
571
        return $vnc;
572
    }
573
574
    public function actionDrawChart()
575
    {
576
        $post = Yii::$app->request->post();
577
        $types = array_merge(['server_traf', 'server_traf95'], array_keys(ResourceConsumption::types()));
578
        if (!in_array($post['type'], $types, true)) {
579
            throw new NotFoundHttpException();
580
        }
581
582
        $searchModel = new ServerUseSearch();
583
        $dataProvider = $searchModel->search([]);
584
        $dataProvider->pagination = false;
585
        $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...
586
        $dataProvider->query->andWhere($post);
587
        $models = $dataProvider->getModels();
588
589
        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...
590
591
        return $this->renderAjax('_consumption', [
592
            'labels' => $labels,
593
            'data' => $data,
594
            'consumptionBase' => $post['type'],
595
        ]);
596
    }
597
598
    /**
599
     * Gets OS images.
600
     *
601
     * @param Server $model
602
     * @throws NotFoundHttpException
603
     * @return array
604
     */
605
    protected function getOsimages(Server $model = null)
606
    {
607
        if ($model !== null) {
608
            $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...
609
        } else {
610
            $type = null;
611
        }
612
613
        $models = ServerHelper::getOsimages($type);
614
615
        if ($models === null) {
616
            throw new NotFoundHttpException('The requested page does not exist.');
617
        }
618
619
        return $models;
620
    }
621
622
    protected function getOsimagesLiveCd()
623
    {
624
        $models = Yii::$app->cache->getOrSet([__METHOD__], function () {
625
            return Osimage::findAll(['livecd' => true]);
626
        }, 3600);
627
628
        if ($models !== null) {
629
            return $models;
630
        }
631
632
        throw new NotFoundHttpException('The requested page does not exist.');
633
    }
634
635
    protected function getPanelTypes()
636
    {
637
        return ServerHelper::getPanels();
638
    }
639
640
    public function actionIsOperable($id)
641
    {
642
        Yii::$app->response->format = Response::FORMAT_JSON;
643
644
        $result = ['id' => $id, 'result' => false];
645
646
        if ($server = Server::find()->where(['id' => $id])->one()) {
647
            $result['result'] = $server->isOperable();
648
        }
649
650
        return $result;
651
    }
652
653 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...
654
    {
655
        $callingMethod = debug_backtrace()[1]['function'];
656
        $result = Yii::$app->get('cache')->getOrSet([$callingMethod], function () use ($gtype) {
657
            $result = ArrayHelper::map(Ref::find()->where([
658
                'gtype' => $gtype,
659
                'select' => 'full',
660
            ])->all(), 'id', function ($model) {
661
                return Yii::t('hipanel:server:hub', $model->label);
662
            });
663
664
            return $result;
665
        }, 86400 * 24); // 24 days
666
667
        return $result;
668
    }
669
670
    public function actionResources($id)
671
    {
672
        $model = Server::find()->joinWith(['uses'])->andWhere(['id' => $id])->andWhere(['with_uses' => 1])->one();
673
        list($chartsLabels, $chartsData) = $model->groupUsesForCharts();
674
675
        return $this->render('resources', compact('model', 'chartsData', 'chartsLabels'));
676
    }
677
}
678