Completed
Push — master ( 6bfe3b...6571ea )
by Andrii
15:55
created

ServerController::actions()   C

Complexity

Conditions 12
Paths 1

Size

Total Lines 324
Code Lines 230

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 153
CRAP Score 19.1646

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 324
ccs 153
cts 242
cp 0.6322
rs 5.034
cc 12
eloc 230
nc 1
nop 0
crap 19.1646

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
/*
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\yii2\cart\actions\AddToCartAction;
37
use Yii;
38
use yii\base\Event;
39
use yii\helpers\ArrayHelper;
40
use yii\web\NotFoundHttpException;
41
use yii\web\Response;
42
43
class ServerController extends CrudController
44 1
{
45
    public function actions()
46
    {
47
        return [
48 1
            'index' => [
49 1
                'class' => IndexAction::class,
50
                'findOptions' => ['with_requests' => true, 'with_discounts' => true],
51
                'on beforePerform' => function (Event $event) {
52
                    /** @var \hipanel\actions\SearchAction $action */
53
                    $action = $event->sender;
54
                    $dataProvider = $action->getDataProvider();
55
                    $dataProvider->query->joinWith('ips');
56
57
                    $dataProvider->query
58
                        ->andWhere(['with_ips' => 1])
59
                        ->andWhere(['with_switches' => 1])
60
                        ->andWhere(['with_requests' => 1])
61
                        ->andWhere(['with_discounts' => 1])
62 1
                        ->select(['*']);
63
                },
64 1
                'filterStorageMap' => [
65 1
                    'name_like' => 'server.server.name',
66 1
                    'ips' => 'hosting.ip.ip_in',
67 1
                    'state' => 'server.server.state',
68 1
                    'client_id' => 'client.client.id',
69 1
                    'seller_id' => 'client.client.seller_id',
70 1
                ],
71
            ],
72 1
            'search' => [
73 1
                'class' => SearchAction::class,
74
            ],
75 1
            'view' => [
76
                'class' => ViewAction::class,
77
                'on beforePerform' => function (Event $event) {
78
                    /** @var \hipanel\actions\SearchAction $action */
79
                    $action = $event->sender;
80
                    $dataProvider = $action->getDataProvider();
81
                    $dataProvider->query->joinWith('uses');
82
                    $dataProvider->query->joinWith('ips');
83
84
                    // TODO: ipModule is not wise yet. Redo
85
                    $dataProvider->query
86
                        ->andWhere(['with_requests' => 1])
87
                        ->andWhere(['show_deleted' => 1])
88
                        ->andWhere(['with_discounts' => 1])
89
                        ->andWhere(['with_uses' => 1])
90
                        ->andWhere(['with_ips' => 1])
91 1
                        ->select(['*']);
92
                },
93
                'data' => function ($action) {
94
                    /**
95
                     * @var Action $action
96
                     * @var self $controller
97
                     * @var Server $model
98
                     */
99
                    $controller = $action->controller;
100
                    $model = $action->getModel();
101
                    $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...
102
103
                    $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...
104
105
                    $tariff = Yii::$app->cache->getAuthTimeCached(3600, [$model->tariff_id], function ($tariff_id) {
106
                        return Tariff::find()->where([
107
                            'id' => $tariff_id,
108
                            'show_final' => true,
109
                            'show_deleted' => true,
110
                            'with_resources' => true,
111
                        ])->joinWith('resources')->one();
112
                    });
113
114
                    $ispSupported = false;
115
                    if ($tariff !== null) {
116
                        foreach ($tariff->getResources() as $resource) {
117
                            if ($resource->type === 'isp' && $resource->quantity > 0) {
118
                                $ispSupported = true;
119
                            }
120
                        }
121
                    }
122
123
                    $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...
124
                    $groupedOsimages = ServerHelper::groupOsimages($osimages, $ispSupported);
125
126
                    if ($model->isLiveCDSupported()) {
127
                        $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...
128
                    }
129
130
                    $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...
131
132
                    return compact([
133
                        'model',
134
                        'osimages',
135
                        'osimageslivecd',
136
                        'groupedOsimages',
137
                        'panels',
138
                        'blockReasons',
139 1
                    ]);
140 1
                },
141
            ],
142 1
            'requests-state' => [
143 1
                'class' => RequestStateAction::class,
144 1
                'model' => Server::class,
145
            ],
146 1
            'set-note' => [
147 1
                'class' => SmartUpdateAction::class,
148 1
                'success' => Yii::t('hipanel/server', 'Note changed'),
149 1
                'error' => Yii::t('hipanel/server', 'Failed to change note'),
150
            ],
151 1
            'set-label' => [
152 1
                'class' => SmartUpdateAction::class,
153 1
                'success' => Yii::t('hipanel/server', 'Internal note changed'),
154 1
                'error' => Yii::t('hipanel/server', 'Failed to change internal note'),
155
            ],
156 1
            'set-lock' => [
157 1
                'class' => RenderAction::class,
158 1
                'success' => Yii::t('hipanel/server', 'Record was changed'),
159
                'error' => Yii::t('hipanel/server', 'Error occurred'),
160 1
                'POST pjax' => [
161
                    'save' => true,
162 1
                    'success' => [
163 1
                        'class' => ProxyAction::class,
164 1
                        'action' => 'index',
165 1
                    ],
166
                ],
167 1
                'POST' => [
168
                    'save' => true,
169 1
                    'success' => [
170
                        'class' => RenderJsonAction::class,
171
                        'return' => function ($action) {
172
                            /** @var \hipanel\actions\Action $action */
173 1
                            return $action->collection->models;
174 1
                        },
175 1
                    ],
176 1
                ],
177
            ],
178 1
            'sale' => [
179 1
                'class' => SmartUpdateAction::class,
180
                'view' => '_saleModal',
181 1
                'POST' => [
182
                    'save' => true,
183 1
                    'success' => [
184
                        'class' => RenderJsonAction::class,
185
                        'return' => function ($action) {
186 1
                            return ['success' => !$action->collection->hasErrors()];
187 1
                        },
188 1
                    ],
189 1
                ],
190
            ],
191 1
            'enable-vnc' => [
192 1
                'class' => ViewAction::class,
193
                'view' => '_vnc',
194
                'data' => function ($action) {
195
                    $model = $action->getModel();
196
                    $model->checkOperable();
197
                    $model->vnc = $action->controller->getVNCInfo($model, true);
198 1
                    return [];
199 1
                },
200
            ],
201 1
            'reboot' => [
202 1
                'class' => SmartUpdateAction::class,
203 1
                'success' => Yii::t('hipanel/server', 'Reboot task has been successfully added to queue'),
204 1
                'error' => Yii::t('hipanel/server', 'Error during the rebooting'),
205
            ],
206 1
            'reset' => [
207 1
                'class' => SmartUpdateAction::class,
208 1
                'success' => Yii::t('hipanel/server', 'Reset task has been successfully added to queue'),
209 1
                'error' => Yii::t('hipanel/server', 'Error during the resetting'),
210
            ],
211 1
            'shutdown' => [
212 1
                'class' => SmartUpdateAction::class,
213 1
                'success' => Yii::t('hipanel/server', 'Shutdown task has been successfully added to queue'),
214 1
                'error' => Yii::t('hipanel/server', 'Error during the shutting down'),
215
            ],
216 1
            'power-off' => [
217 1
                'class' => SmartUpdateAction::class,
218 1
                'success' => Yii::t('hipanel/server', 'Power off task has been successfully added to queue'),
219 1
                'error' => Yii::t('hipanel/server', 'Error during the turning power off'),
220
            ],
221 1
            'power-on' => [
222 1
                'class' => SmartUpdateAction::class,
223 1
                'success' => Yii::t('hipanel/server', 'Power on task has been successfully added to queue'),
224 1
                'error' => Yii::t('hipanel/server', 'Error during the turning power on'),
225
            ],
226 1
            'reset-password' => [
227 1
                'class' => SmartUpdateAction::class,
228 1
                'success' => Yii::t('hipanel/server', 'Root password reset task has been successfully added to queue'),
229 1
                'error' => Yii::t('hipanel/server', 'Error during the resetting root password'),
230
            ],
231 1
            'enable-block' => [
232 1
                'class' => SmartUpdateAction::class,
233 1
                'success' => Yii::t('hipanel/server', 'Server was blocked successfully'),
234 1
                'error' => Yii::t('hipanel/server', 'Error during the server blocking'),
235
            ],
236 1
            'disable-block' => [
237 1
                'class' => SmartUpdateAction::class,
238 1
                'success' => Yii::t('hipanel/server', 'Server was unblocked successfully'),
239 1
                'error' => Yii::t('hipanel/server', 'Error during the server unblocking'),
240
            ],
241 1
            'refuse' => [
242 1
                'class' => SmartUpdateAction::class,
243 1
                'success' => Yii::t('hipanel/server', 'You have refused the service'),
244 1
                'error' => Yii::t('hipanel/server', 'Error during the refusing the service'),
245
            ],
246 1
            'enable-autorenewal' => [
247 1
                'class' => SmartUpdateAction::class,
248 1
                'success' => Yii::t('hipanel/server', 'Server renewal enabled successfully'),
249 1
                'error' => Yii::t('hipanel/server', 'Error during the renewing the service'),
250
            ],
251 1
            'reinstall' => [
252
                'class' => SmartUpdateAction::class,
253
                'on beforeSave' => function (Event $event) {
254
                    /** @var Action $action */
255
                    $action = $event->sender;
256
                    foreach ($action->collection->models as $model) {
257
                        $model->osimage = Yii::$app->request->post('osimage');
258
                        $model->panel = Yii::$app->request->post('panel');
259 1
                    }
260 1
                },
261 1
                'success' => Yii::t('hipanel/server', 'Server reinstalling task has been successfully added to queue'),
262 1
                'error' => Yii::t('hipanel/server', 'Error during the server reinstalling'),
263
            ],
264 1
            'boot-live' => [
265
                'class' => SmartUpdateAction::class,
266
                'on beforeSave' => function (Event $event) {
267
                    /** @var Action $action */
268
                    $action = $event->sender;
269
                    foreach ($action->collection->models as $model) {
270
                        $model->osimage = Yii::$app->request->post('osimage');
271 1
                    }
272 1
                },
273 1
                'success' => Yii::t('hipanel/server', 'Live CD booting task has been successfully added to queue'),
274 1
                'error' => Yii::t('hipanel/server', 'Error during the booting live CD'),
275
            ],
276 1
            'validate-form' => [
277 1
                'class' => ValidateFormAction::class,
278
            ],
279 1
            'buy' => [
280 1
                'class' => RedirectAction::class,
281 1
                'url' => Yii::$app->params['orgUrl'],
282
            ],
283 1
            'add-to-cart-renewal' => [
284 1
                'class' => AddToCartAction::class,
285 1
                'productClass' => ServerRenewProduct::class,
286
            ],
287 1
            'delete' => [
288 1
                'class' => SmartDeleteAction::class,
289 1
                'success' => Yii::t('hipanel/server', 'Server was deleted successfully'),
290 1
                'error' => Yii::t('hipanel/server', 'Failed to delete server'),
291
            ],
292 1
            'bulk-delete-modal' => [
293 1
                'class' => PrepareBulkAction::class,
294 1
                'scenario' => 'delete',
295 1
                'view' => '_bulkDelete',
296
            ],
297 1
            'bulk-enable-block' => [
298 1
                'class' => SmartUpdateAction::class,
299 1
                'scenario' => 'enable-block',
300 1
                'success' => Yii::t('hipanel/server', 'Servers were blocked successfully'),
301
                'error' => Yii::t('hipanel/server', 'Error during the servers blocking'),
302 1
                'POST html' => [
303
                    'save'    => true,
304 1
                    'success' => [
305 1
                        'class' => RedirectAction::class,
306 1
                    ],
307
                ],
308
                'on beforeSave' => function (Event $event) {
309
                    /** @var \hipanel\actions\Action $action */
310
                    $action = $event->sender;
311
                    $type = Yii::$app->request->post('type');
312
                    $comment = Yii::$app->request->post('comment');
313
                    if (!empty($type)) {
314
                        foreach ($action->collection->models as $model) {
315
                            $model->setAttributes([
316
                                'type' => $type,
317
                                'comment' => $comment,
318
                            ]);
319
                        }
320 1
                    }
321 1
                },
322
            ],
323 1
            'bulk-enable-block-modal' => [
324 1
                'class' => PrepareBulkAction::class,
325 1
                'scenario' => 'enable-block',
326
                'view' => '_bulkEnableBlock',
327
                'data' => function ($action, $data) {
328
                    return array_merge($data, [
329
                        'blockReasons' => $this->getBlockReasons(),
330 1
                    ]);
331 1
                },
332
            ],
333 1
            'bulk-disable-block' => [
334 1
                'class' => SmartUpdateAction::class,
335 1
                'scenario' => 'disable-block',
336 1
                'success' => Yii::t('hipanel/server', 'Servers were unblocked successfully'),
337
                'error' => Yii::t('hipanel/server', 'Error during the servers unblocking'),
338 1
                'POST html' => [
339
                    'save'    => true,
340 1
                    'success' => [
341 1
                        'class' => RedirectAction::class,
342 1
                    ],
343
                ],
344
                'on beforeSave' => function (Event $event) {
345
                    /** @var \hipanel\actions\Action $action */
346
                    $action = $event->sender;
347
                    $comment = Yii::$app->request->post('comment');
348
                    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...
349
                        foreach ($action->collection->models as $model) {
350
                            $model->setAttribute('comment', $comment);
351
                        }
352 1
                    }
353 1
                },
354
            ],
355 1
            'bulk-disable-block-modal' => [
356 1
                'class' => PrepareBulkAction::class,
357 1
                'scenario' => 'disable-block',
358 1
                'view' => '_bulkDisableBlock',
359
            ],
360 1
            'set-orientation' => [
361
                'class' => OrientationAction::class,
362 1
                'allowedRoutes' => [
363 1
                    '@server/index'
364 1
                ]
365
            ]
366 1
367
        ];
368
    }
369
370
    /**
371
     * Gets info of VNC on the server.
372
     *
373
     * @param Server $model
374
     * @param bool $enable
375
     *
376
     * @return array
377
     */
378
    public function getVNCInfo($model, $enable = false)
379
    {
380
        $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...
Coding Style Comprehensibility introduced by
$vnc was never initialized. Although not strictly required by PHP, it is generally a good practice to add $vnc = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
381
        if (($vnc['endTime'] > time() || $enable) && $model->isOperable()) {
382
            $vnc['enabled'] = true;
383
            $vnc = ArrayHelper::merge($vnc, Server::perform('EnableVNC', ['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...
384
        }
385
386
        return $vnc;
387
    }
388
389
    public function actionDrawChart()
390
    {
391
        $post = Yii::$app->request->post();
392
        if (!in_array($post['type'], ['traffic', 'bandwidth'], true)) {
393
            throw new NotFoundHttpException();
394
        }
395
396
        $searchModel = new ServerUseSearch();
397
        $dataProvider = $searchModel->search([]);
398
        $dataProvider->pagination = false;
399
        $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...
400
        $dataProvider->query->andWhere($post);
401
        $models = $dataProvider->getModels();
402
403
        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...
404
405
        return $this->renderAjax('_' . $post['type'] . '_consumption', [
406
            'labels' => $labels,
407
            'data' => $data,
408
        ]);
409
    }
410
411
    /**
412
     * Gets OS images.
413
     *
414
     * @param Server $model
415
     * @throws NotFoundHttpException
416
     * @return array
417
     */
418
    protected function getOsimages(Server $model = null)
419
    {
420
        if ($model !== null) {
421
            $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...
422
        } else {
423
            $type = null;
424
        }
425
426
        $models = ServerHelper::getOsimages($type);
427
428
        if ($models === null) {
429
            throw new NotFoundHttpException('The requested page does not exist.');
430
        }
431
432
        return $models;
433
    }
434
435
    protected function getOsimagesLiveCd()
436
    {
437
        $models = Yii::$app->cache->getTimeCached(3600, [true], function ($livecd) {
438
            return Osimage::findAll(['livecd' => $livecd]);
439
        });
440
441
        if ($models !== null) {
442
            return $models;
443
        }
444
445
        throw new NotFoundHttpException('The requested page does not exist.');
446
    }
447
448
    protected function getPanelTypes()
449
    {
450
        return ServerHelper::getPanels();
451
    }
452
453
    public function actionIsOperable($id)
454
    {
455
        Yii::$app->response->format = Response::FORMAT_JSON;
456
457
        $result = ['id' => $id, 'result' => false];
458
459
        if ($server = Server::find()->where(['id' => $id])->one()) {
460
            $result['result'] = $server->isOperable();
461
        }
462
463
        return $result;
464
    }
465
}
466