Completed
Push — master ( 9ea30c...5bd098 )
by Dmitry
15:07
created

IpGridView::columns()   C

Complexity

Conditions 12
Paths 1

Size

Total Lines 128
Code Lines 87

Duplication

Lines 14
Ratio 10.94 %

Code Coverage

Tests 0
CRAP Score 156

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 14
loc 128
ccs 0
cts 108
cp 0
rs 5.034
cc 12
eloc 87
nc 1
nop 0
crap 156

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
 * Hosting Plugin for HiPanel
4
 *
5
 * @link      https://github.com/hiqdev/hipanel-module-hosting
6
 * @package   hipanel-module-hosting
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2015-2016, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hipanel\modules\hosting\grid;
12
13
use hipanel\grid\MainColumn;
14
use hipanel\helpers\FontIcon;
15
use hipanel\helpers\Url;
16
use hipanel\modules\hosting\menus\IpActionsMenu;
17
use hipanel\modules\hosting\models\HdomainSearch;
18
use hipanel\modules\hosting\widgets\ip\IpTag;
19
use hipanel\widgets\ArraySpoiler;
20
use hipanel\widgets\XEditable;
21
use hiqdev\yii2\menus\grid\MenuColumn;
22
use Yii;
23
use yii\base\InvalidParamException;
24
use yii\helpers\Html;
25
use hipanel\grid\XEditableColumn;
26
27
class IpGridView extends \hipanel\grid\BoxedGridView
28
{
29
    public $controllerUrl = '@ip';
30
31
    public $ipTags = [];
32
33
    public function columns()
34
    {
35
        return array_merge(parent::columns(), [
36
            'ip' => [
37
                'class' => MainColumn::class,
38
                'filterAttribute' => 'ip_like',
39
            ],
40
            'note' => [
41
                'class' => XEditableColumn::class,
42
                'pluginOptions' => [
43
                    'url'       => Url::to('set-note'),
44
                ],
45
                'widgetOptions' => [
46
                    'linkOptions' => [
47
                        'data-type' => 'textarea',
48
                    ],
49
                ],
50
                'visible' => Yii::$app->user->can('admin'),
51
            ],
52
            'tags' => [
53
                'format' => 'raw',
54
                'attribute' => 'tag',
55
                'header' => Yii::t('hipanel:hosting', 'Tags'),
56
                'visible' => Yii::$app->user->can('admin'),
57
                'filter' => function ($column, $model) {
58
                    return Html::activeDropDownList($model, 'tag_in', array_merge(['' => Yii::t('hipanel', '---')], $this->ipTags), ['class' => 'form-control']);
59
                },
60
                'value' => function ($model) {
61
                    $labels = [];
62
                    foreach ($model->tags as $tag) {
63
                        $labels[] = IpTag::widget(['tag' => $tag]);
64
                    }
65
                    return implode(' ', $labels);
66
                },
67
            ],
68
            'counters' => [
69
                'format' => 'html',
70
                'header' => Yii::t('hipanel:hosting', 'Counters'),
71
                'value' => function ($model) {
72
                    $html = '';
73
                    foreach ($model->objects_count as $count) {
74
                        if ($count['type'] === 'hdomain') {
75
                            $url['ok'] = ['@hdomain', (new HdomainSearch())->formName() => ['ip_like' => $model->ip]];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$url was never initialized. Although not strictly required by PHP, it is generally a good practice to add $url = 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...
76
                            $url['deleted'] = ['@hdomain', (new HdomainSearch())->formName() => ['ip_like' => $model->ip, 'state' => 'deleted']];
0 ignored issues
show
Bug introduced by
The variable $url does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
77
                            $type = function ($count) {
78
                                return Yii::t('hipanel:hosting', '{0, plural, one{domain} other{domains}}', (int) $count);
0 ignored issues
show
Documentation introduced by
(int) $count is of type integer, but the function expects a array.

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...
79
                            };
80
                        } else {
81
                            throw new InvalidParamException('The object type is not supported', $model);
82
                        }
83
84 View Code Duplication
                        if ($count['ok']) {
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...
85
                            $html .= Html::a(
86
                                (int) $count['ok'] . '&nbsp;' . FontIcon::i('fa-check') . ' ' . $type($count['ok']),
87
                                $url['ok'],
88
                                ['class' => 'btn btn-success btn-xs']
89
                            );
90
                        }
91
                        $html .= ' ';
92 View Code Duplication
                        if ($count['deleted'] > 0) {
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...
93
                            $html .= Html::a(
94
                                (int) $count['deleted'] . '&nbsp;' . FontIcon::i('fa-trash') . ' ' . $type($count['deleted']),
95
                                $url['deleted'],
96
                                ['class' => 'btn btn-xs btn-warning']
97
                            );
98
                        }
99
                    }
100
101
                    return $html;
102
                },
103
            ],
104
            'links' => [
105
                'format' => 'html',
106
                'value' => function ($model) {
107
                    $items = [];
108
                    foreach ($model->links as $link) {
109
                        $item = Html::a($link->device, ['@server/view', 'id' => $link->device_id]);
110
                        if ($link->service_id) {
111
                            $item .= '&nbsp;' . FontIcon::i('fa-long-arrow-right');
112
                            $item .= '&nbsp;' . Html::a($link->service ?: $link->soft, ['@service/view', 'id' => $link->service_id]);
113
                        }
114
                        $items[] = $item;
115
                    }
116
                    return ArraySpoiler::widget(['data' => $items, 'visibleCount' => 3]);
117
                },
118
            ],
119
            'services' => [
120
                'attribute' => 'links',
121
                'format' => 'html',
122
                'label' => Yii::t('hipanel:server', 'Services'),
123
                'value' => function ($model) {
124
                    return ArraySpoiler::widget([
125
                        'data' => $model->links,
126
                        'formatter' => function ($link) {
127
                            if (Yii::$app->user->can('support') && Yii::getAlias('@service', false)) {
128
                                return Html::a($link->service, ['@service/view', 'id' => $link->service_id]);
129
                            }
130
131
                            return $link->service;
132
                        },
133
                    ]);
134
                },
135
            ],
136
            'actions' => [
137
                'class' => MenuColumn::class,
138
                'menuClass' => IpActionsMenu::class,
139
            ],
140
            'ptr' => [
141
                'options' => [
142
                    'style' => 'width: 40%',
143
                ],
144
                'format' => 'raw',
145
                'value' => function ($model) {
146
                    if ($model->canSetPtr()) {
147
                        return XEditable::widget([
148
                            'model' => $model,
149
                            'attribute' => 'ptr',
150
                            'pluginOptions' => [
151
                                'url' => Url::to('@ip/set-ptr'),
152
                            ],
153
                        ]);
154
                    }
155
156
                    return null;
157
                },
158
            ],
159
        ]);
160
    }
161
}
162