Completed
Push — master ( 54947b...6a07df )
by Dmitry
04:48
created

ServerController   C

Complexity

Total Complexity 29

Size/Duplication

Total Lines 433
Duplicated Lines 6.93 %

Coupling/Cohesion

Components 0
Dependencies 20

Test Coverage

Coverage 55.45%

Importance

Changes 2
Bugs 0 Features 1
Metric Value
wmc 29
c 2
b 0
f 1
lcom 0
cbo 20
dl 30
loc 433
ccs 56
cts 101
cp 0.5545
rs 6.4705

7 Methods

Rating   Name   Duplication   Size   Complexity  
A getPanelTypes() 0 4 1
D actions() 30 327 13
B getVNCInfo() 0 17 6
A actionDrawChart() 0 21 2
A getOsimages() 0 16 3
A getOsimagesLiveCd() 0 12 2
A actionIsOperable() 0 12 2

How to fix   Duplicated Code   

Duplicated Code

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

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/*
4
 * Server module for HiPanel
5
 *
6
 * @link      https://github.com/hiqdev/hipanel-module-server
7
 * @package   hipanel-module-server
8
 * @license   BSD-3-Clause
9
 * @copyright Copyright (c) 2015-2016, HiQDev (http://hiqdev.com/)
10
 */
11
12
namespace hipanel\modules\server\controllers;
13
14
use hipanel\actions\Action;
15
use hipanel\actions\IndexAction;
16
use hipanel\actions\OrientationAction;
17
use hipanel\actions\PrepareBulkAction;
18
use hipanel\actions\ProxyAction;
19
use hipanel\actions\RedirectAction;
20
use hipanel\actions\RenderAction;
21
use hipanel\actions\RenderJsonAction;
22
use hipanel\actions\RequestStateAction;
23
use hipanel\actions\SearchAction;
24
use hipanel\actions\SmartDeleteAction;
25
use hipanel\actions\SmartUpdateAction;
26
use hipanel\actions\ValidateFormAction;
27
use hipanel\actions\ViewAction;
28
use hipanel\base\CrudController;
29
use hipanel\models\Ref;
30
use hipanel\modules\finance\models\Tariff;
31
use hipanel\modules\server\cart\ServerRenewProduct;
32
use hipanel\modules\server\helpers\ServerHelper;
33
use hipanel\modules\server\models\Osimage;
34
use hipanel\modules\server\models\Server;
35
use hipanel\modules\server\models\ServerUseSearch;
36
use hiqdev\hiart\ResponseErrorException;
37
use hiqdev\yii2\cart\actions\AddToCartAction;
38
use Yii;
39
use yii\base\Event;
40
use yii\helpers\ArrayHelper;
41
use yii\web\NotFoundHttpException;
42
use yii\web\Response;
43
44
class ServerController extends CrudController
45
{
46 1
    public function actions()
47
    {
48
        return [
49
            'index' => [
50
                'class' => IndexAction::class,
51
                'findOptions' => ['with_requests' => true, 'with_discounts' => true],
52 View Code Duplication
                'on beforePerform' => 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...
53
                    /** @var \hipanel\actions\SearchAction $action */
54
                    $action = $event->sender;
55
                    $dataProvider = $action->getDataProvider();
56
                    $dataProvider->query->joinWith('ips');
57
58
                    $dataProvider->query
59
                        ->andWhere(['with_ips' => 1])
60
                        ->andWhere(['with_tariffs' => 1])
61
                        ->andWhere(['with_switches' => 1])
62
                        ->andWhere(['with_requests' => 1])
63
                        ->andWhere(['with_discounts' => 1])
64
                        ->select(['*']);
65 1
                },
66
                'filterStorageMap' => [
67
                    'name_like' => 'server.server.name',
68
                    'ips' => 'hosting.ip.ip_in',
69
                    'state' => 'server.server.state',
70
                    'client_id' => 'client.client.id',
71
                    'seller_id' => 'client.client.seller_id',
72
                ],
73 1
            ],
74
            'search' => [
75
                'class' => SearchAction::class,
76
            ],
77
            'view' => [
78
                'class' => ViewAction::class,
79 View Code Duplication
                'on beforePerform' => 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...
80
                    /** @var \hipanel\actions\SearchAction $action */
81
                    $action = $event->sender;
82
                    $dataProvider = $action->getDataProvider();
83
                    $dataProvider->query->joinWith('uses');
84
                    $dataProvider->query->joinWith('ips');
85
86
                    // TODO: ipModule is not wise yet. Redo
87
                    $dataProvider->query
88
                        ->andWhere(['with_requests' => 1])
89
                        ->andWhere(['show_deleted' => 1])
90
                        ->andWhere(['with_discounts' => 1])
91
                        ->andWhere(['with_uses' => 1])
92
                        ->andWhere(['with_ips' => 1])
93
                        ->select(['*']);
94 1
                },
95
                'data' => function ($action) {
96
                    /**
97
                     * @var Action $action
98
                     * @var self $controller
99
                     * @var Server $model
100
                     */
101
                    $controller = $action->controller;
102
                    $model = $action->getModel();
103
                    $model->vnc = $controller->getVNCInfo($model);
0 ignored issues
show
Documentation Bug introduced by
The method getVNCInfo does not exist on object<hipanel\modules\s...art\ServerRenewProduct>? 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...
104
105
                    $panels = $controller->getPanelTypes();
0 ignored issues
show
Documentation Bug introduced by
The method getPanelTypes does not exist on object<hipanel\modules\s...art\ServerRenewProduct>? 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...
106
107
                    $tariff = Yii::$app->cache->getAuthTimeCached(3600, [$model->tariff_id], function ($tariff_id) {
108
                        return Tariff::find()->where([
109
                            'id' => $tariff_id,
110
                            'show_final' => true,
111
                            'show_deleted' => true,
112
                            'with_resources' => true,
113
                        ])->joinWith('resources')->one();
114
                    });
115
116
                    $ispSupported = false;
117
                    if ($tariff !== null) {
118
                        foreach ($tariff->getResources() as $resource) {
119
                            if ($resource->type === 'isp' && $resource->quantity > 0) {
120
                                $ispSupported = true;
121
                            }
122
                        }
123
                    }
124
125
                    $osimages = $controller->getOsimages($model);
0 ignored issues
show
Documentation Bug introduced by
The method getOsimages does not exist on object<hipanel\modules\s...art\ServerRenewProduct>? 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...
126
                    $groupedOsimages = ServerHelper::groupOsimages($osimages, $ispSupported);
127
128
                    if ($model->isLiveCDSupported()) {
129
                        $osimageslivecd = $controller->getOsimagesLiveCd();
0 ignored issues
show
Documentation Bug introduced by
The method getOsimagesLiveCd does not exist on object<hipanel\modules\s...art\ServerRenewProduct>? 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...
130
                    }
131
132
                    $blockReasons = $controller->getBlockReasons();
0 ignored issues
show
Documentation Bug introduced by
The method getBlockReasons does not exist on object<hipanel\modules\s...art\ServerRenewProduct>? 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...
133
134
                    return compact([
135
                        'model',
136
                        'osimages',
137
                        'osimageslivecd',
138
                        'groupedOsimages',
139
                        'panels',
140
                        'blockReasons',
141
                    ]);
142 1
                },
143
            ],
144
            'requests-state' => [
145
                'class' => RequestStateAction::class,
146
                'model' => Server::class,
147
            ],
148
            'set-note' => [
149
                'class' => SmartUpdateAction::class,
150 1
                'success' => Yii::t('hipanel:server', 'Note changed'),
151 1
                'error' => Yii::t('hipanel:server', 'Failed to change note'),
152
            ],
153
            'set-label' => [
154
                'class' => SmartUpdateAction::class,
155 1
                'success' => Yii::t('hipanel:server', 'Internal note changed'),
156 1
                'error' => Yii::t('hipanel:server', 'Failed to change internal note'),
157
            ],
158
            'set-lock' => [
159
                'class' => RenderAction::class,
160 1
                'success' => Yii::t('hipanel:server', 'Record was changed'),
161 1
                'error' => Yii::t('hipanel:server', 'Error occurred'),
162
                'POST pjax' => [
163
                    'save' => true,
164
                    'success' => [
165
                        'class' => ProxyAction::class,
166
                        'action' => 'index',
167
                    ],
168
                ],
169
                'POST' => [
170
                    'save' => true,
171
                    'success' => [
172
                        'class' => RenderJsonAction::class,
173
                        'return' => function ($action) {
174
                            /** @var \hipanel\actions\Action $action */
175
                            return $action->collection->models;
176 1
                        },
177
                    ],
178
                ],
179
            ],
180
            'sale' => [
181
                'class' => SmartUpdateAction::class,
182 1
                'view' => '_saleModal',
183
                'POST' => [
184
                    'save' => true,
185
                    'success' => [
186
                        'class' => RenderJsonAction::class,
187
                        'return' => function ($action) {
188
                            return ['success' => !$action->collection->hasErrors()];
189 1
                        },
190
                    ],
191
                ],
192
            ],
193
            'enable-vnc' => [
194
                'class' => ViewAction::class,
195 1
                'view' => '_vnc',
196
                'data' => function ($action) {
197
                    $model = $action->getModel();
198
                    if ($model->canEnableVNC()) {
199
                        $model->vnc = $this->getVNCInfo($model, true);
200
                    }
201
202
                    return [];
203 1
                },
204
            ],
205
            'reboot' => [
206
                'class' => SmartUpdateAction::class,
207 1
                'success' => Yii::t('hipanel:server', 'Reboot task has been successfully added to queue'),
208 1
                'error' => Yii::t('hipanel:server', 'Error during the rebooting'),
209
            ],
210
            'reset' => [
211
                'class' => SmartUpdateAction::class,
212 1
                'success' => Yii::t('hipanel:server', 'Reset task has been successfully added to queue'),
213 1
                'error' => Yii::t('hipanel:server', 'Error during the resetting'),
214
            ],
215
            'shutdown' => [
216
                'class' => SmartUpdateAction::class,
217 1
                'success' => Yii::t('hipanel:server', 'Shutdown task has been successfully added to queue'),
218 1
                'error' => Yii::t('hipanel:server', 'Error during the shutting down'),
219
            ],
220
            'power-off' => [
221
                'class' => SmartUpdateAction::class,
222 1
                'success' => Yii::t('hipanel:server', 'Power off task has been successfully added to queue'),
223 1
                'error' => Yii::t('hipanel:server', 'Error during the turning power off'),
224
            ],
225
            'power-on' => [
226
                'class' => SmartUpdateAction::class,
227 1
                'success' => Yii::t('hipanel:server', 'Power on task has been successfully added to queue'),
228 1
                'error' => Yii::t('hipanel:server', 'Error during the turning power on'),
229
            ],
230
            'reset-password' => [
231
                'class' => SmartUpdateAction::class,
232 1
                'success' => Yii::t('hipanel:server', 'Root password reset task has been successfully added to queue'),
233 1
                'error' => Yii::t('hipanel:server', 'Error during the resetting root password'),
234
            ],
235
            'enable-block' => [
236
                'class' => SmartUpdateAction::class,
237 1
                'success' => Yii::t('hipanel:server', 'Server was blocked successfully'),
238 1
                'error' => Yii::t('hipanel:server', 'Error during the server blocking'),
239
            ],
240
            'disable-block' => [
241
                'class' => SmartUpdateAction::class,
242 1
                'success' => Yii::t('hipanel:server', 'Server was unblocked successfully'),
243 1
                'error' => Yii::t('hipanel:server', 'Error during the server unblocking'),
244
            ],
245
            'refuse' => [
246
                'class' => SmartUpdateAction::class,
247 1
                'success' => Yii::t('hipanel:server', 'You have refused the service'),
248 1
                'error' => Yii::t('hipanel:server', 'Error during the refusing the service'),
249
            ],
250
            'enable-autorenewal' => [
251
                'class' => SmartUpdateAction::class,
252 1
                'success' => Yii::t('hipanel:server', 'Server renewal enabled successfully'),
253 1
                'error' => Yii::t('hipanel:server', 'Error during the renewing the service'),
254
            ],
255
            'reinstall' => [
256
                'class' => SmartUpdateAction::class,
257
                'on beforeSave' => function (Event $event) {
258
                    /** @var Action $action */
259
                    $action = $event->sender;
260
                    foreach ($action->collection->models as $model) {
261
                        $model->osimage = Yii::$app->request->post('osimage');
262
                        $model->panel = Yii::$app->request->post('panel');
263
                    }
264 1
                },
265 1
                'success' => Yii::t('hipanel:server', 'Server reinstalling task has been successfully added to queue'),
266 1
                'error' => Yii::t('hipanel:server', 'Error during the server reinstalling'),
267
            ],
268
            'boot-live' => [
269
                'class' => SmartUpdateAction::class,
270
                'on beforeSave' => function (Event $event) {
271
                    /** @var Action $action */
272
                    $action = $event->sender;
273
                    foreach ($action->collection->models as $model) {
274
                        $model->osimage = Yii::$app->request->post('osimage');
275
                    }
276 1
                },
277 1
                'success' => Yii::t('hipanel:server', 'Live CD booting task has been successfully added to queue'),
278 1
                'error' => Yii::t('hipanel:server', 'Error during the booting live CD'),
279
            ],
280
            'validate-form' => [
281
                'class' => ValidateFormAction::class,
282
            ],
283
            'buy' => [
284
                'class' => RedirectAction::class,
285 1
                'url' => Yii::$app->params['orgUrl'],
286
            ],
287
            'add-to-cart-renewal' => [
288
                'class' => AddToCartAction::class,
289
                'productClass' => ServerRenewProduct::class,
290
            ],
291
            'delete' => [
292
                'class' => SmartDeleteAction::class,
293 1
                'success' => Yii::t('hipanel:server', 'Server was deleted successfully'),
294 1
                'error' => Yii::t('hipanel:server', 'Failed to delete server'),
295
            ],
296
            'bulk-delete-modal' => [
297
                'class' => PrepareBulkAction::class,
298
                'scenario' => 'delete',
299
                'view' => '_bulkDelete',
300
            ],
301
            'bulk-enable-block' => [
302
                'class' => SmartUpdateAction::class,
303 1
                'scenario' => 'enable-block',
304 1
                'success' => Yii::t('hipanel:server', 'Servers were blocked successfully'),
305 1
                'error' => Yii::t('hipanel:server', 'Error during the servers blocking'),
306
                'POST html' => [
307
                    'save'    => true,
308
                    'success' => [
309
                        'class' => RedirectAction::class,
310
                    ],
311
                ],
312
                'on beforeSave' => function (Event $event) {
313
                    /** @var \hipanel\actions\Action $action */
314
                    $action = $event->sender;
315
                    $type = Yii::$app->request->post('type');
316
                    $comment = Yii::$app->request->post('comment');
317
                    if (!empty($type)) {
318
                        foreach ($action->collection->models as $model) {
319
                            $model->setAttributes([
320
                                'type' => $type,
321
                                'comment' => $comment,
322
                            ]);
323
                        }
324
                    }
325 1
                },
326
            ],
327
            'bulk-enable-block-modal' => [
328
                'class' => PrepareBulkAction::class,
329 1
                'scenario' => 'enable-block',
330 1
                'view' => '_bulkEnableBlock',
331
                'data' => function ($action, $data) {
332
                    return array_merge($data, [
333
                        'blockReasons' => $this->getBlockReasons(),
334
                    ]);
335 1
                },
336
            ],
337
            'bulk-disable-block' => [
338
                'class' => SmartUpdateAction::class,
339 1
                'scenario' => 'disable-block',
340 1
                'success' => Yii::t('hipanel:server', 'Servers were unblocked successfully'),
341 1
                'error' => Yii::t('hipanel:server', 'Error during the servers unblocking'),
342
                'POST html' => [
343
                    'save'    => true,
344
                    'success' => [
345
                        'class' => RedirectAction::class,
346
                    ],
347
                ],
348
                'on beforeSave' => function (Event $event) {
349
                    /** @var \hipanel\actions\Action $action */
350
                    $action = $event->sender;
351
                    $comment = Yii::$app->request->post('comment');
352
                    if (!empty($type)) {
0 ignored issues
show
Bug introduced by
The variable $type seems to never exist, and therefore empty should always return true. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
353
                        foreach ($action->collection->models as $model) {
354
                            $model->setAttribute('comment', $comment);
355
                        }
356
                    }
357 1
                },
358
            ],
359
            'bulk-disable-block-modal' => [
360
                'class' => PrepareBulkAction::class,
361
                'scenario' => 'disable-block',
362
                'view' => '_bulkDisableBlock',
363
            ],
364
            'set-orientation' => [
365
                'class' => OrientationAction::class,
366
                'allowedRoutes' => [
367
                    '@server/index'
368
                ]
369
            ]
370
371
        ];
372
    }
373
374
    /**
375
     * Gets info of VNC on the server.
376
     *
377
     * @param Server $model
378
     * @param bool $enable
379
     * @return array
380
     * @throws ResponseErrorException
381
     */
382
    public function getVNCInfo($model, $enable = false)
383
    {
384
        $vnc = ['endTime' => strtotime('+8 hours', strtotime($model->statuses['serverEnableVNC']))];
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...
385
        if ($model->canEnableVnc() && $vnc['endTime'] > time() || $enable) {
386
            try {
387
                $vnc = ArrayHelper::merge($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...
388
                $vnc['enabled'] = true;
389
            } catch (ResponseErrorException $e) {
390
                if ($e->getMessage() !== 'vds_has_tasks') { // expected error, that could be skipped
391
                    throw $e;
392
                }
393
                $vnc['enabled'] = false;
394
            }
395
        }
396
397
        return $vnc;
398
    }
399
400
    public function actionDrawChart()
401
    {
402
        $post = Yii::$app->request->post();
403
        if (!in_array($post['type'], ['traffic', 'bandwidth'], true)) {
404
            throw new NotFoundHttpException();
405
        }
406
407
        $searchModel = new ServerUseSearch();
408
        $dataProvider = $searchModel->search([]);
409
        $dataProvider->pagination = false;
410
        $dataProvider->query->options = ['scenario' => 'get-uses'];
0 ignored issues
show
Bug introduced by
Accessing options on the interface yii\db\QueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
411
        $dataProvider->query->andWhere($post);
412
        $models = $dataProvider->getModels();
413
414
        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...
415
416
        return $this->renderAjax('_' . $post['type'] . '_consumption', [
417
            'labels' => $labels,
418
            'data' => $data,
419
        ]);
420
    }
421
422
    /**
423
     * Gets OS images.
424
     *
425
     * @param Server $model
426
     * @throws NotFoundHttpException
427
     * @return array
428
     */
429
    protected function getOsimages(Server $model = null)
430
    {
431
        if ($model !== null) {
432
            $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...
433
        } else {
434
            $type = null;
435
        }
436
437
        $models = ServerHelper::getOsimages($type);
438
439
        if ($models === null) {
440
            throw new NotFoundHttpException('The requested page does not exist.');
441
        }
442
443
        return $models;
444
    }
445
446
    protected function getOsimagesLiveCd()
447
    {
448
        $models = Yii::$app->cache->getTimeCached(3600, [true], function ($livecd) {
449
            return Osimage::findAll(['livecd' => $livecd]);
450
        });
451
452
        if ($models !== null) {
453
            return $models;
454
        }
455
456
        throw new NotFoundHttpException('The requested page does not exist.');
457
    }
458
459
    protected function getPanelTypes()
460
    {
461
        return ServerHelper::getPanels();
462
    }
463
464
    public function actionIsOperable($id)
465
    {
466
        Yii::$app->response->format = Response::FORMAT_JSON;
467
468
        $result = ['id' => $id, 'result' => false];
469
470
        if ($server = Server::find()->where(['id' => $id])->one()) {
471
            $result['result'] = $server->isOperable();
472
        }
473
474
        return $result;
475
    }
476
}
477