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