Completed
Push — master ( f38efd...4bc8e5 )
by Klochok
05:16
created

ServerController::actionDrawChart()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 21
ccs 0
cts 13
cp 0
rs 9.3142
cc 2
eloc 14
nc 2
nop 0
crap 6
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
    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
                },
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
            ],
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
                },
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
                },
164
            ],
165
            'requests-state' => [
166
                'class' => RequestStateAction::class,
167
                'model' => Server::class,
168
            ],
169
            'set-note' => [
170
                'class' => SmartUpdateAction::class,
171
                'success' => Yii::t('hipanel:server', 'Note changed'),
172
                'error' => Yii::t('hipanel:server', 'Failed to change note'),
173
            ],
174
            'set-label' => [
175
                'class' => SmartUpdateAction::class,
176
                'success' => Yii::t('hipanel:server', 'Internal note changed'),
177
                'error' => Yii::t('hipanel:server', 'Failed to change internal note'),
178
            ],
179
            'set-lock' => [
180
                'class' => RenderAction::class,
181
                'success' => Yii::t('hipanel:server', 'Record was changed'),
182
                '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
                        },
198
                    ],
199
                ],
200
            ],
201
            'sale' => [
202
                'class' => SmartUpdateAction::class,
203
                'view' => '_saleModal',
204
                'POST' => [
205
                    'save' => true,
206
                    'success' => [
207
                        'class' => RenderJsonAction::class,
208
                        'return' => function ($action) {
209
                            return ['success' => !$action->collection->hasErrors()];
210
                        },
211
                    ],
212
                ],
213
            ],
214
            'enable-vnc' => [
215
                'class' => ViewAction::class,
216
                '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
                },
225
            ],
226
            'reboot' => [
227
                'class' => SmartPerformAction::class,
228
                'success' => Yii::t('hipanel:server', 'Reboot task has been successfully added to queue'),
229
                'error' => Yii::t('hipanel:server', 'Error during the rebooting'),
230
            ],
231
            'reset' => [
232
                'class' => SmartPerformAction::class,
233
                'success' => Yii::t('hipanel:server', 'Reset task has been successfully added to queue'),
234
                'error' => Yii::t('hipanel:server', 'Error during the resetting'),
235
            ],
236
            'shutdown' => [
237
                'class' => SmartPerformAction::class,
238
                'success' => Yii::t('hipanel:server', 'Shutdown task has been successfully added to queue'),
239
                'error' => Yii::t('hipanel:server', 'Error during the shutting down'),
240
            ],
241
            'power-off' => [
242
                'class' => SmartPerformAction::class,
243
                'success' => Yii::t('hipanel:server', 'Power off task has been successfully added to queue'),
244
                'error' => Yii::t('hipanel:server', 'Error during the turning power off'),
245
            ],
246
            'power-on' => [
247
                'class' => SmartPerformAction::class,
248
                'success' => Yii::t('hipanel:server', 'Power on task has been successfully added to queue'),
249
                'error' => Yii::t('hipanel:server', 'Error during the turning power on'),
250
            ],
251
            'reset-password' => [
252
                'class' => SmartPerformAction::class,
253
                'success' => Yii::t('hipanel:server', 'Root password reset task has been successfully added to queue'),
254
                'error' => Yii::t('hipanel:server', 'Error during the resetting root password'),
255
            ],
256
            'enable-block' => [
257
                'class' => SmartPerformAction::class,
258
                'success' => Yii::t('hipanel:server', 'Server was blocked successfully'),
259
                'error' => Yii::t('hipanel:server', 'Error during the server blocking'),
260
            ],
261
            'disable-block' => [
262
                'class' => SmartPerformAction::class,
263
                'success' => Yii::t('hipanel:server', 'Server was unblocked successfully'),
264
                'error' => Yii::t('hipanel:server', 'Error during the server unblocking'),
265
            ],
266
            'refuse' => [
267
                'class' => SmartPerformAction::class,
268
                'success' => Yii::t('hipanel:server', 'You have refused the service'),
269
                'error' => Yii::t('hipanel:server', 'Error during the refusing the service'),
270
            ],
271
            'enable-autorenewal' => [
272
                'class' => SmartUpdateAction::class,
273
                'success' => Yii::t('hipanel:server', 'Server renewal enabled successfully'),
274
                '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
                },
286
                'success' => Yii::t('hipanel:server', 'Server reinstalling task has been successfully added to queue'),
287
                '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
                },
298
                'success' => Yii::t('hipanel:server', 'Live CD booting task has been successfully added to queue'),
299
                '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
                '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
                'success' => Yii::t('hipanel:server', 'Server was deleted successfully'),
315
                '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
                'scenario' => 'enable-block',
325
                'success' => Yii::t('hipanel:server', 'Servers were blocked successfully'),
326
                '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
                },
347
            ],
348
            'bulk-enable-block-modal' => [
349
                'class' => PrepareBulkAction::class,
350
                'scenario' => 'enable-block',
351
                'view' => '_bulkEnableBlock',
352
                'data' => function ($action, $data) {
353
                    return array_merge($data, [
354
                        'blockReasons' => $this->getBlockReasons(),
355
                    ]);
356
                },
357
            ],
358
            'bulk-disable-block' => [
359
                'class' => SmartUpdateAction::class,
360
                'scenario' => 'disable-block',
361
                'success' => Yii::t('hipanel:server', 'Servers were unblocked successfully'),
362
                '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
                },
379
            ],
380
            'bulk-disable-block-modal' => [
381
                'class' => PrepareBulkAction::class,
382
                'scenario' => 'disable-block',
383
                'view' => '_bulkDisableBlock',
384
            ],
385
        ];
386
    }
387
388
    /**
389
     * Gets info of VNC on the server.
390
     *
391
     * @param Server $model
392
     * @param bool $enable
393
     * @throws ResponseErrorException
394
     * @return array
395
     */
396
    public function getVNCInfo($model, $enable = false)
397
    {
398
        $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...
399
        if ($model->canEnableVnc() && $vnc['endTime'] > time() || $enable) {
400
            try {
401
                $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...
402
                $vnc['enabled'] = true;
403
            } catch (ResponseErrorException $e) {
404
                if ($e->getMessage() !== 'vds_has_tasks') { // expected error, that could be skipped
405
                    throw $e;
406
                }
407
                $vnc['enabled'] = false;
408
            }
409
        }
410
411
        return $vnc;
412
    }
413
414
    public function actionDrawChart()
415
    {
416
        $post = Yii::$app->request->post();
417
        if (!in_array($post['type'], ['traffic', 'bandwidth'], true)) {
418
            throw new NotFoundHttpException();
419
        }
420
421
        $searchModel = new ServerUseSearch();
422
        $dataProvider = $searchModel->search([]);
423
        $dataProvider->pagination = false;
424
        $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...
425
        $dataProvider->query->andWhere($post);
426
        $models = $dataProvider->getModels();
427
428
        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...
429
430
        return $this->renderAjax('_' . $post['type'] . '_consumption', [
431
            'labels' => $labels,
432
            'data' => $data,
433
        ]);
434
    }
435
436
    /**
437
     * Gets OS images.
438
     *
439
     * @param Server $model
440
     * @throws NotFoundHttpException
441
     * @return array
442
     */
443
    protected function getOsimages(Server $model = null)
444
    {
445
        if ($model !== null) {
446
            $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...
447
        } else {
448
            $type = null;
449
        }
450
451
        $models = ServerHelper::getOsimages($type);
452
453
        if ($models === null) {
454
            throw new NotFoundHttpException('The requested page does not exist.');
455
        }
456
457
        return $models;
458
    }
459
460
    protected function getOsimagesLiveCd()
461
    {
462
        $models = Yii::$app->cache->getOrSet([__METHOD__], function () {
463
            return Osimage::findAll(['livecd' => true]);
464
        }, 3600);
465
466
        if ($models !== null) {
467
            return $models;
468
        }
469
470
        throw new NotFoundHttpException('The requested page does not exist.');
471
    }
472
473
    protected function getPanelTypes()
474
    {
475
        return ServerHelper::getPanels();
476
    }
477
478
    public function actionIsOperable($id)
479
    {
480
        Yii::$app->response->format = Response::FORMAT_JSON;
481
482
        $result = ['id' => $id, 'result' => false];
483
484
        if ($server = Server::find()->where(['id' => $id])->one()) {
485
            $result['result'] = $server->isOperable();
486
        }
487
488
        return $result;
489
    }
490
}
491