Completed
Push — master ( 9fa729...e15551 )
by Dmitry
13:25
created

ServerGridView::columns()   D

Complexity

Conditions 14
Paths 1

Size

Total Lines 224
Code Lines 160

Duplication

Lines 23
Ratio 10.27 %

Code Coverage

Tests 0
CRAP Score 210

Importance

Changes 0
Metric Value
dl 23
loc 224
ccs 0
cts 200
cp 0
rs 4.9516
c 0
b 0
f 0
cc 14
eloc 160
nc 1
nop 0
crap 210

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\grid;
12
13
use hipanel\grid\MainColumn;
14
use hipanel\grid\RefColumn;
15
use hipanel\grid\XEditableColumn;
16
use hipanel\helpers\Url;
17
use hipanel\modules\hosting\controllers\AccountController;
18
use hipanel\modules\hosting\controllers\IpController;
19
use hipanel\modules\server\menus\ServerActionsMenu;
20
use hipanel\modules\server\models\Binding;
21
use hipanel\modules\server\widgets\DiscountFormatter;
22
use hipanel\modules\server\widgets\Expires;
23
use hipanel\modules\server\widgets\OSFormatter;
24
use hipanel\modules\server\widgets\State;
25
use hipanel\widgets\ArraySpoiler;
26
use hipanel\widgets\Label;
27
use hiqdev\yii2\menus\grid\MenuColumn;
28
use Yii;
29
use yii\helpers\ArrayHelper;
30
use yii\helpers\Html;
31
32
class ServerGridView extends \hipanel\grid\BoxedGridView
33
{
34
    public $controllerUrl = '@server';
35
36
    /**
37
     * @var array
38
     */
39
    public $osImages;
40
41
    protected function formatTariff($model)
42
    {
43
        if (Yii::$app->user->can('manage')) {
44
            if ($model->parent_tariff) {
45
                $html[] = Html::tag('abbr', $model->parent_tariff, ['title' => $model->tariff, 'data-toggle' => 'tooltip']);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$html was never initialized. Although not strictly required by PHP, it is generally a good practice to add $html = 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...
46
            } else {
47
                $html[] = $model->tariff;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$html was never initialized. Although not strictly required by PHP, it is generally a good practice to add $html = 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...
48
            }
49
50
            $html[] = Html::a('<i class="fa fa-external-link"></i>', ['@tariff/view', 'id' => $model->tariff_id]);
51
52
            return implode(' ', $html);
53
        }
54
55
        return !empty($model->parent_tariff) ? $model->parent_tariff : $model->tariff;
56
    }
57
58
    public function columns()
59
    {
60
        $osImages = $this->osImages;
61
62
        return array_merge(parent::columns(), [
0 ignored issues
show
Bug introduced by
The method columns() does not exist on hipanel\grid\BoxedGridView. Did you maybe mean column()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
63
            'server' => [
64
                'class' => MainColumn::class,
65
                'attribute' => 'name',
66
                'filterAttribute' => 'name_like',
67
                'note' => Yii::$app->user->can('support') ? 'label' : 'note',
68
                'noteOptions' => [
69
                    'url' => Yii::$app->user->can('support') ? Url::to('set-label') : Url::to('set-note'),
70
                ],
71
                'badges' => function ($model) {
72
                    $badges = '';
73 View Code Duplication
                    if (Yii::$app->user->can('support')) {
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...
74
                        if ($model->wizzarded) {
75
                            $badges .= Label::widget(['label' => 'W', 'tag' => 'sup', 'color' => 'success']);
76
                        }
77
                    }
78
79
                    return $badges;
80
                },
81
            ],
82
            'dc' => [
83
                'attribute' => 'dc',
84
                'filter' => false,
85
            ],
86
            'state' => [
87
                'class' => RefColumn::class,
88
                'i18nDictionary' => 'hipanel:server',
89
                'format' => 'raw',
90
                'gtype' => 'state,device',
91
                'value' => function ($model) {
92
                    $html = State::widget(compact('model'));
93
                    if ($model->status_time) {
94
                        $html .= ' ' . Html::tag('nobr', Yii::t('hipanel:server', 'since {date}', ['date' => Yii::$app->formatter->asDate($model->status_time)]));
95
                    }
96
                    return $html;
97
                },
98
            ],
99
            'panel' => [
100
                'attribute' => 'panel',
101
                'format' => 'html',
102
                'contentOptions' => ['class' => 'text-uppercase'],
103
                'value' => function ($model) {
104
                    $value = $model->panel ? Yii::t('hipanel:server:panel', $model->panel) : Yii::t('hipanel:server:panel', 'No control panel');
105 View Code Duplication
                    if (Yii::$app->user->can('support')) {
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...
106
                        $value .= $model->wizzarded ? Label::widget(['label' => 'W', 'tag' => 'sup', 'color' => 'success']) : '';
107
                    }
108
109
                    return $value;
110
                },
111
            ],
112
            'os' => [
113
                'attribute' => 'os',
114
                'format' => 'raw',
115
                'value' => function ($model) use ($osImages) {
116
                    return OSFormatter::widget([
117
                        'osimages' => $osImages,
118
                        'imageName' => $model->osimage,
119
                    ]);
120
                },
121
            ],
122
            'os_and_panel' => [
123
                'attribute' => 'os',
124
                'format' => 'raw',
125
                'value' => function ($model) use ($osImages) {
126
                    $html = OSFormatter::widget([
127
                        'osimages' => $osImages,
128
                        'imageName' => $model->osimage,
129
                    ]);
130
                    $html .= ' ' . $model->panel ?: '';
131
                    return $html;
132
                },
133
            ],
134
            'discount' => [
135
                'attribute' => 'discount',
136
                'label' => Yii::t('hipanel:server', 'Discount'),
137
                'format' => 'raw',
138
                'headerOptions' => ['style' => 'width: 1em'],
139 View Code Duplication
                'value' => function ($model) {
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...
140
                    return DiscountFormatter::widget([
141
                        'current' => $model->discounts['fee']['current'],
142
                        'next' => $model->discounts['fee']['next'],
143
                    ]);
144
                },
145
            ],
146
            'expires' => [
147
                'filter' => false,
148
                'format' => 'raw',
149
                'headerOptions' => ['style' => 'width: 1em'],
150
                'value' => function ($model) {
151
                    return Expires::widget(compact('model'));
152
                },
153
            ],
154
            'tariff' => [
155
                'format' => 'raw',
156
                'filterAttribute' => 'tariff_like',
157
                'value' => function ($model) {
158
                    return $this->formatTariff($model);
159
                },
160
            ],
161
            'tariff_and_discount' => [
162
                'attribute' => 'tariff',
163
                'filterAttribute' => 'tariff_like',
164
                'format' => 'raw',
165 View Code Duplication
                'value' => function ($model) {
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...
166
                    return $this->formatTariff($model) . ' ' . DiscountFormatter::widget([
167
                        'current' => $model->discounts['fee']['current'],
168
                        'next' => $model->discounts['fee']['next'],
169
                    ]);
170
                },
171
            ],
172
            'ip' => [
173
                'filter' => false,
174
            ],
175
            'mac' => [
176
                'filter' => false,
177
            ],
178
            'ips' => [
179
                'format' => 'raw',
180
                'attribute' => 'ips',
181
                'filter' => false,
182
                'value' => function ($model) {
183
                    return ArraySpoiler::widget([
184
                        'data' => ArrayHelper::getColumn($model->ips, 'ip'),
185
                        'delimiter' => '<br />',
186
                        'visibleCount' => 3,
187
                        'button' => ['popoverOptions' => ['html' => true]],
188
                    ]);
189
                },
190
            ],
191
            'sale_time' => [
192
                'attribute' => 'sale_time',
193
                'format' => 'datetime',
194
            ],
195
            'note' => [
196
                'class' => XEditableColumn::class,
197
                'pluginOptions' => [
198
                    'url'       => Url::to('set-note'),
199
                ],
200
                'widgetOptions' => [
201
                    'linkOptions' => [
202
                        'data-type' => 'textarea',
203
                    ],
204
                ],
205
            ],
206
            'label' => [
207
                'class' => XEditableColumn::class,
208
                'visible' => Yii::$app->user->can('support'),
209
                'pluginOptions' => [
210
                    'url'       => Url::to('set-label'),
211
                ],
212
                'widgetOptions' => [
213
                    'linkOptions' => [
214
                        'data-type' => 'textarea',
215
                    ],
216
                ],
217
            ],
218
            'type' => [
219
                'format' => 'html',
220
                'filter' => false,
221
                'value'  => function ($model) {
222
                    return $model->type_label;
223
                },
224
            ],
225
            'rack' => [
226
                'format' => 'html',
227
                'filter' => false,
228
                'value'  => function ($model) {
229
                    return $this->renderSwitchPort($model->bindings['rack']);
230
                },
231
            ],
232
            'net' => [
233
                'format' => 'html',
234
                'filter' => false,
235
                'value'  => function ($model) {
236
                    return $this->renderSwitchPort($model->bindings['net']);
237
                },
238
            ],
239
            'kvm' => [
240
                'format' => 'html',
241
                'filter' => false,
242
                'value'  => function ($model) {
243
                    return $this->renderSwitchPort($model->bindings['kvm']);
244
                },
245
            ],
246
            'pdu' => [
247
                'format' => 'html',
248
                'filter' => false,
249
                'value'  => function ($model) {
250
                    return $this->renderSwitchPort($model->bindings['pdu']);
251
                },
252
            ],
253
            'ipmi' => [
254
                'format' => 'raw',
255
                'filter' => false,
256
                'value'  => function ($model) {
257
                    if (($ipmi = $model->getBinding('ipmi')) !== null) {
258
                        $link = Html::a($ipmi->device_ip, "http://$ipmi->device_ip/", ['target' => '_blank']) . ' ';
259
                        return $link . $this->renderSwitchPort($ipmi);
260
                    }
261
                },
262
            ],
263
            'nums' => [
264
                'label' => '',
265
                'format' => 'raw',
266
                'value' => function ($model) {
267
                    $ips_num = $model->ips_num;
268
                    $ips = $ips_num ? Html::a("$ips_num ips", IpController::getSearchUrl(['server' => $model->name])) : 'no ips';
269
                    $act_acs_num = $model->acs_num - $model->del_acs_num;
270
                    $del_acs_num = $model->del_acs_num;
271
                    $acs_num = $act_acs_num . ($del_acs_num ? "+$del_acs_num" : '');
272
                    $acs = $acs_num ? Html::a("$acs_num acc", AccountController::getSearchUrl(['server' => $model->name])) : 'no acc';
273
                    return Html::tag('nobr', $ips) . ' ' . Html::tag('nobr', $acs);
274
                },
275
            ],
276
            'actions' => [
277
                'class' => MenuColumn::class,
278
                'menuClass' => ServerActionsMenu::class,
279
            ],
280
        ]);
281
    }
282
283
    /**
284
     * @param Binding $binding
285
     * @return string
286
     */
287
    protected function renderSwitchPort($binding)
288
    {
289
        if ($binding === null) {
290
            return '';
291
        }
292
293
        $label  = $binding->switch_label;
0 ignored issues
show
Documentation introduced by
The property switch_label does not exist on object<hipanel\modules\server\models\Binding>. 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...
294
        $inn    = $binding->switch_inn;
0 ignored issues
show
Documentation introduced by
The property switch_inn does not exist on object<hipanel\modules\server\models\Binding>. 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...
295
        $inn    = $inn ? "($inn) " : '';
296
        $main   = $binding->switch . ($binding->port ? ':' . $binding->port : '');
0 ignored issues
show
Documentation introduced by
The property switch does not exist on object<hipanel\modules\server\models\Binding>. 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...
Documentation introduced by
The property port does not exist on object<hipanel\modules\server\models\Binding>. 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...
297
298
        return "$inn<b>$main</b> $label";
299
    }
300
}
301