Completed
Push — master ( 00aab8...5fa9a0 )
by Dmitry
15:49 queued 13:14
created

ServerController::actions()   D

Complexity

Conditions 13
Paths 1

Size

Total Lines 327
Code Lines 232

Duplication

Lines 30
Ratio 9.17 %

Code Coverage

Tests 56
CRAP Score 13

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 30
loc 327
ccs 56
cts 56
cp 1
rs 4.9922
cc 13
eloc 232
nc 1
nop 0
crap 13

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\OrientationAction;
17
use hipanel\actions\PrepareBulkAction;
18
use hipanel\actions\ProxyAction;
19
use hipanel\actions\RedirectAction;
20
use hipanel\actions\RenderAction;
21
use hipanel\actions\RenderJsonAction;
22
use hipanel\actions\RequestStateAction;
23
use hipanel\actions\SmartDeleteAction;
24
use hipanel\actions\SmartPerformAction;
25
use hipanel\actions\SmartUpdateAction;
26
use hipanel\actions\ValidateFormAction;
27
use hipanel\actions\ViewAction;
28
use hipanel\base\CrudController;
29
use hipanel\modules\finance\models\Tariff;
30
use hipanel\modules\server\cart\ServerRenewProduct;
31
use hipanel\modules\server\helpers\ServerHelper;
32
use hipanel\modules\server\models\Osimage;
33
use hipanel\modules\server\models\Server;
34
use hipanel\modules\server\models\ServerUseSearch;
35
use hiqdev\hiart\ResponseErrorException;
36
use hiqdev\yii2\cart\actions\AddToCartAction;
37
use Yii;
38
use yii\base\Event;
39
use yii\filters\VerbFilter;
40
use yii\helpers\ArrayHelper;
41
use yii\web\NotFoundHttpException;
42
use yii\web\Response;
43
44
class ServerController extends CrudController
45
{
46
    public function behaviors()
47
    {
48
        return array_merge(parent::behaviors(), [
49
            'server-actions-verb' => [
50
                'class' => VerbFilter::class,
51
                'actions' => [
52
                    'reboot' => ['post'],
53
                    'reset' => ['post'],
54
                    'shutdown' => ['post'],
55
                    'power-off' => ['post'],
56
                    'power-on' => ['post'],
57
                    'reset-password' => ['post'],
58
                    'enable-block' => ['post'],
59
                    'disable-block' => ['post'],
60
                    'refuse' => ['post'],
61
                ],
62
            ],
63
        ]);
64
    }
65
66 1
    public function actions()
67
    {
68
        return [
69
            'index' => [
70
                'class' => IndexAction::class,
71
                'findOptions' => ['with_requests' => true, 'with_discounts' => true],
72 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...
73
                    /** @var \hipanel\actions\SearchAction $action */
74
                    $action = $event->sender;
75
                    $dataProvider = $action->getDataProvider();
76
                    $dataProvider->query->joinWith('ips');
77
78
                    $dataProvider->query
79
                        ->andWhere(['with_ips' => 1])
80
                        ->andWhere(['with_tariffs' => 1])
81
                        ->andWhere(['with_switches' => 1])
82
                        ->andWhere(['with_requests' => 1])
83
                        ->andWhere(['with_discounts' => 1])
84
                        ->select(['*']);
85 1
                },
86
                'filterStorageMap' => [
87
                    'name_like' => 'server.server.name',
88
                    'ips' => 'hosting.ip.ip_in',
89
                    'state' => 'server.server.state',
90
                    'client_id' => 'client.client.id',
91
                    'seller_id' => 'client.client.seller_id',
92
                ],
93 1
            ],
94
            'search' => [
95
                'class' => ComboSearchAction::class,
96
            ],
97
            'view' => [
98
                'class' => ViewAction::class,
99 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...
100
                    /** @var \hipanel\actions\SearchAction $action */
101
                    $action = $event->sender;
102
                    $dataProvider = $action->getDataProvider();
103
                    $dataProvider->query->joinWith('uses');
104
                    $dataProvider->query->joinWith('ips');
105
106
                    // TODO: ipModule is not wise yet. Redo
107
                    $dataProvider->query
108
                        ->andWhere(['with_requests' => 1])
109
                        ->andWhere(['show_deleted' => 1])
110
                        ->andWhere(['with_discounts' => 1])
111
                        ->andWhere(['with_uses' => 1])
112
                        ->andWhere(['with_ips' => 1])
113
                        ->select(['*']);
114 1
                },
115
                'data' => function ($action) {
116
                    /**
117
                     * @var Action $action
118
                     * @var self $controller
119
                     * @var Server $model
120
                     */
121
                    $controller = $action->controller;
122
                    $model = $action->getModel();
123
                    $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...
124
125
                    $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...
126
127
                    $cacheKeys = [__METHOD__, 'view', 'tariff', $model->tariff_id, Yii::$app->user->getId()];
128
                    $tariff = Yii::$app->cache->getOrSet($cacheKeys, function () use ($model) {
129
                        return Tariff::find()->where([
130
                            'id' => $model->tariff_id,
131
                            'show_final' => true,
132
                            'show_deleted' => true,
133
                            'with_resources' => true,
134
                        ])->joinWith('resources')->one();
135
                    });
136
137
                    $ispSupported = false;
138
                    if ($tariff !== null) {
139
                        foreach ($tariff->getResources() as $resource) {
140
                            if ($resource->type === 'isp' && $resource->quantity > 0) {
141
                                $ispSupported = true;
142
                            }
143
                        }
144
                    }
145
146
                    $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...
147
                    $groupedOsimages = ServerHelper::groupOsimages($osimages, $ispSupported);
148
149
                    if ($model->isLiveCDSupported()) {
150
                        $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...
151
                    }
152
153
                    $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...
154
155
                    return compact([
156
                        'model',
157
                        'osimages',
158
                        'osimageslivecd',
159
                        'groupedOsimages',
160
                        'panels',
161
                        'blockReasons',
162
                    ]);
163 1
                },
164
            ],
165
            'requests-state' => [
166
                'class' => RequestStateAction::class,
167
                'model' => Server::class,
168
            ],
169
            'set-note' => [
170
                'class' => SmartUpdateAction::class,
171 1
                'success' => Yii::t('hipanel:server', 'Note changed'),
172 1
                'error' => Yii::t('hipanel:server', 'Failed to change note'),
173
            ],
174
            'set-label' => [
175
                'class' => SmartUpdateAction::class,
176 1
                'success' => Yii::t('hipanel:server', 'Internal note changed'),
177 1
                'error' => Yii::t('hipanel:server', 'Failed to change internal note'),
178
            ],
179
            'set-lock' => [
180
                'class' => RenderAction::class,
181 1
                'success' => Yii::t('hipanel:server', 'Record was changed'),
182 1
                'error' => Yii::t('hipanel:server', 'Error occurred'),
183
                'POST pjax' => [
184
                    'save' => true,
185
                    'success' => [
186
                        'class' => ProxyAction::class,
187
                        'action' => 'index',
188
                    ],
189
                ],
190
                'POST' => [
191
                    'save' => true,
192
                    'success' => [
193
                        'class' => RenderJsonAction::class,
194
                        'return' => function ($action) {
195
                            /** @var \hipanel\actions\Action $action */
196
                            return $action->collection->models;
197 1
                        },
198
                    ],
199
                ],
200
            ],
201
            'sale' => [
202
                'class' => SmartUpdateAction::class,
203 1
                'view' => '_saleModal',
204
                'POST' => [
205
                    'save' => true,
206
                    'success' => [
207
                        'class' => RenderJsonAction::class,
208
                        'return' => function ($action) {
209
                            return ['success' => !$action->collection->hasErrors()];
210 1
                        },
211
                    ],
212
                ],
213
            ],
214
            'enable-vnc' => [
215
                'class' => ViewAction::class,
216 1
                'view' => '_vnc',
217
                'data' => function ($action) {
218
                    $model = $action->getModel();
219
                    if ($model->canEnableVNC()) {
220
                        $model->vnc = $this->getVNCInfo($model, true);
221
                    }
222
223
                    return [];
224 1
                },
225
            ],
226
            'reboot' => [
227
                'class' => SmartPerformAction::class,
228 1
                'success' => Yii::t('hipanel:server', 'Reboot task has been successfully added to queue'),
229 1
                'error' => Yii::t('hipanel:server', 'Error during the rebooting'),
230
            ],
231
            'reset' => [
232
                'class' => SmartPerformAction::class,
233 1
                'success' => Yii::t('hipanel:server', 'Reset task has been successfully added to queue'),
234 1
                'error' => Yii::t('hipanel:server', 'Error during the resetting'),
235
            ],
236
            'shutdown' => [
237
                'class' => SmartPerformAction::class,
238 1
                'success' => Yii::t('hipanel:server', 'Shutdown task has been successfully added to queue'),
239 1
                'error' => Yii::t('hipanel:server', 'Error during the shutting down'),
240
            ],
241
            'power-off' => [
242
                'class' => SmartPerformAction::class,
243 1
                'success' => Yii::t('hipanel:server', 'Power off task has been successfully added to queue'),
244 1
                'error' => Yii::t('hipanel:server', 'Error during the turning power off'),
245
            ],
246
            'power-on' => [
247
                'class' => SmartPerformAction::class,
248 1
                'success' => Yii::t('hipanel:server', 'Power on task has been successfully added to queue'),
249 1
                'error' => Yii::t('hipanel:server', 'Error during the turning power on'),
250
            ],
251
            'reset-password' => [
252
                'class' => SmartPerformAction::class,
253 1
                'success' => Yii::t('hipanel:server', 'Root password reset task has been successfully added to queue'),
254 1
                'error' => Yii::t('hipanel:server', 'Error during the resetting root password'),
255
            ],
256
            'enable-block' => [
257
                'class' => SmartPerformAction::class,
258 1
                'success' => Yii::t('hipanel:server', 'Server was blocked successfully'),
259 1
                'error' => Yii::t('hipanel:server', 'Error during the server blocking'),
260
            ],
261
            'disable-block' => [
262
                'class' => SmartPerformAction::class,
263 1
                'success' => Yii::t('hipanel:server', 'Server was unblocked successfully'),
264 1
                'error' => Yii::t('hipanel:server', 'Error during the server unblocking'),
265
            ],
266
            'refuse' => [
267
                'class' => SmartPerformAction::class,
268 1
                'success' => Yii::t('hipanel:server', 'You have refused the service'),
269 1
                'error' => Yii::t('hipanel:server', 'Error during the refusing the service'),
270
            ],
271
            'enable-autorenewal' => [
272
                'class' => SmartUpdateAction::class,
273 1
                'success' => Yii::t('hipanel:server', 'Server renewal enabled successfully'),
274 1
                'error' => Yii::t('hipanel:server', 'Error during the renewing the service'),
275
            ],
276
            'reinstall' => [
277
                'class' => SmartUpdateAction::class,
278
                'on beforeSave' => function (Event $event) {
279
                    /** @var Action $action */
280
                    $action = $event->sender;
281
                    foreach ($action->collection->models as $model) {
282
                        $model->osimage = Yii::$app->request->post('osimage');
283
                        $model->panel = Yii::$app->request->post('panel');
284
                    }
285 1
                },
286 1
                'success' => Yii::t('hipanel:server', 'Server reinstalling task has been successfully added to queue'),
287 1
                'error' => Yii::t('hipanel:server', 'Error during the server reinstalling'),
288
            ],
289
            'boot-live' => [
290
                'class' => SmartPerformAction::class,
291
                'on beforeSave' => function (Event $event) {
292
                    /** @var Action $action */
293
                    $action = $event->sender;
294
                    foreach ($action->collection->models as $model) {
295
                        $model->osimage = Yii::$app->request->post('osimage');
296
                    }
297 1
                },
298 1
                'success' => Yii::t('hipanel:server', 'Live CD booting task has been successfully added to queue'),
299 1
                'error' => Yii::t('hipanel:server', 'Error during the booting live CD'),
300
            ],
301
            'validate-form' => [
302
                'class' => ValidateFormAction::class,
303
            ],
304
            'buy' => [
305
                'class' => RedirectAction::class,
306 1
                'url' => Yii::$app->params['orgUrl'],
307
            ],
308
            'add-to-cart-renewal' => [
309
                'class' => AddToCartAction::class,
310
                'productClass' => ServerRenewProduct::class,
311
            ],
312
            'delete' => [
313
                'class' => SmartDeleteAction::class,
314 1
                'success' => Yii::t('hipanel:server', 'Server was deleted successfully'),
315 1
                'error' => Yii::t('hipanel:server', 'Failed to delete server'),
316
            ],
317
            'bulk-delete-modal' => [
318
                'class' => PrepareBulkAction::class,
319
                'scenario' => 'delete',
320
                'view' => '_bulkDelete',
321
            ],
322
            'bulk-enable-block' => [
323
                'class' => SmartUpdateAction::class,
324 1
                'scenario' => 'enable-block',
325 1
                'success' => Yii::t('hipanel:server', 'Servers were blocked successfully'),
326 1
                'error' => Yii::t('hipanel:server', 'Error during the servers blocking'),
327
                'POST html' => [
328
                    'save'    => true,
329
                    'success' => [
330
                        'class' => RedirectAction::class,
331
                    ],
332
                ],
333
                'on beforeSave' => function (Event $event) {
334
                    /** @var \hipanel\actions\Action $action */
335
                    $action = $event->sender;
336
                    $type = Yii::$app->request->post('type');
337
                    $comment = Yii::$app->request->post('comment');
338
                    if (!empty($type)) {
339
                        foreach ($action->collection->models as $model) {
340
                            $model->setAttributes([
341
                                'type' => $type,
342
                                'comment' => $comment,
343
                            ]);
344
                        }
345
                    }
346 1
                },
347
            ],
348
            'bulk-enable-block-modal' => [
349
                'class' => PrepareBulkAction::class,
350 1
                'scenario' => 'enable-block',
351 1
                'view' => '_bulkEnableBlock',
352
                'data' => function ($action, $data) {
353
                    return array_merge($data, [
354
                        'blockReasons' => $this->getBlockReasons(),
355
                    ]);
356 1
                },
357
            ],
358
            'bulk-disable-block' => [
359
                'class' => SmartUpdateAction::class,
360 1
                'scenario' => 'disable-block',
361 1
                'success' => Yii::t('hipanel:server', 'Servers were unblocked successfully'),
362 1
                'error' => Yii::t('hipanel:server', 'Error during the servers unblocking'),
363
                'POST html' => [
364
                    'save'    => true,
365
                    'success' => [
366
                        'class' => RedirectAction::class,
367
                    ],
368
                ],
369
                'on beforeSave' => function (Event $event) {
370
                    /** @var \hipanel\actions\Action $action */
371
                    $action = $event->sender;
372
                    $comment = Yii::$app->request->post('comment');
373
                    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...
374
                        foreach ($action->collection->models as $model) {
375
                            $model->setAttribute('comment', $comment);
376
                        }
377
                    }
378 1
                },
379
            ],
380
            'bulk-disable-block-modal' => [
381
                'class' => PrepareBulkAction::class,
382
                'scenario' => 'disable-block',
383
                'view' => '_bulkDisableBlock',
384
            ],
385
            'set-orientation' => [
386
                'class' => OrientationAction::class,
387
                'allowedRoutes' => [
388
                    '@server/index',
389
                ],
390
            ],
391
        ];
392
    }
393
394
    /**
395
     * Gets info of VNC on the server.
396
     *
397
     * @param Server $model
398
     * @param bool $enable
399
     * @throws ResponseErrorException
400
     * @return array
401
     */
402
    public function getVNCInfo($model, $enable = false)
403
    {
404
        $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...
405
        if ($model->canEnableVnc() && $vnc['endTime'] > time() || $enable) {
406
            try {
407
                $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...
408
                $vnc['enabled'] = true;
409
            } catch (ResponseErrorException $e) {
410
                if ($e->getMessage() !== 'vds_has_tasks') { // expected error, that could be skipped
411
                    throw $e;
412
                }
413
                $vnc['enabled'] = false;
414
            }
415
        }
416
417
        return $vnc;
418
    }
419
420
    public function actionDrawChart()
421
    {
422
        $post = Yii::$app->request->post();
423
        if (!in_array($post['type'], ['traffic', 'bandwidth'], true)) {
424
            throw new NotFoundHttpException();
425
        }
426
427
        $searchModel = new ServerUseSearch();
428
        $dataProvider = $searchModel->search([]);
429
        $dataProvider->pagination = false;
430
        $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...
431
        $dataProvider->query->andWhere($post);
432
        $models = $dataProvider->getModels();
433
434
        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...
435
436
        return $this->renderAjax('_' . $post['type'] . '_consumption', [
437
            'labels' => $labels,
438
            'data' => $data,
439
        ]);
440
    }
441
442
    /**
443
     * Gets OS images.
444
     *
445
     * @param Server $model
446
     * @throws NotFoundHttpException
447
     * @return array
448
     */
449
    protected function getOsimages(Server $model = null)
450
    {
451
        if ($model !== null) {
452
            $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...
453
        } else {
454
            $type = null;
455
        }
456
457
        $models = ServerHelper::getOsimages($type);
458
459
        if ($models === null) {
460
            throw new NotFoundHttpException('The requested page does not exist.');
461
        }
462
463
        return $models;
464
    }
465
466
    protected function getOsimagesLiveCd()
467
    {
468
        $models = Yii::$app->cache->getOrSet([__METHOD__], function () {
469
            return Osimage::findAll(['livecd' => true]);
470
        }, 3600);
471
472
        if ($models !== null) {
473
            return $models;
474
        }
475
476
        throw new NotFoundHttpException('The requested page does not exist.');
477
    }
478
479
    protected function getPanelTypes()
480
    {
481
        return ServerHelper::getPanels();
482
    }
483
484
    public function actionIsOperable($id)
485
    {
486
        Yii::$app->response->format = Response::FORMAT_JSON;
487
488
        $result = ['id' => $id, 'result' => false];
489
490
        if ($server = Server::find()->where(['id' => $id])->one()) {
491
            $result['result'] = $server->isOperable();
492
        }
493
494
        return $result;
495
    }
496
}
497