Completed
Push — master ( 45ab26...059109 )
by Andrii
05:13
created

IpGridView::defaultColumns()   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 10
Bugs 0 Features 1
Metric Value
c 10
b 0
f 1
dl 14
loc 128
ccs 0
cts 115
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
/*
4
 * Hosting Plugin for HiPanel
5
 *
6
 * @link      https://github.com/hiqdev/hipanel-module-hosting
7
 * @package   hipanel-module-hosting
8
 * @license   BSD-3-Clause
9
 * @copyright Copyright (c) 2015-2016, HiQDev (http://hiqdev.com/)
10
 */
11
12
namespace hipanel\modules\hosting\grid;
13
14
use hipanel\grid\ActionColumn;
15
use hipanel\grid\MainColumn;
16
use hipanel\helpers\FontIcon;
17
use hipanel\helpers\Url;
18
use hipanel\modules\hosting\models\HdomainSearch;
19
use hipanel\modules\hosting\widgets\ip\IpTag;
20
use hipanel\widgets\ArraySpoiler;
21
use hipanel\widgets\XEditable;
22
use Yii;
23
use yii\base\InvalidParamException;
24
use yii\helpers\Html;
25
26
class IpGridView extends \hipanel\grid\BoxedGridView
27
{
28
    public $controllerUrl = '@ip';
29
30
    public static $ipTags = [];
31
32
    public static function setIpTags($ipTags)
33
    {
34
        static::$ipTags = $ipTags;
35
    }
36
37
    public static function defaultColumns()
38
    {
39
        return [
0 ignored issues
show
Bug Best Practice introduced by
The return type of return array('ip' => arr...} return null; })); (array<string,array>) is incompatible with the return type of the parent method hipanel\grid\GridView::defaultColumns of type array<string,array>.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
40
            'ip' => [
41
                'class' => MainColumn::class,
42
                'filterAttribute' => 'ip_like',
43
            ],
44
            'tags' => [
45
                'format' => 'raw',
46
                'attribute' => 'tag',
47
                'header' => Yii::t('hipanel/hosting', 'Tags'),
48
                'filter' => function ($column, $model) {
49
                    return Html::activeDropDownList($model, 'tag_in', array_merge(['' => Yii::t('app', '---')], static::$ipTags), ['class' => 'form-control']);
50
                },
51
                'value' => function ($model) {
52
                    $labels = [];
53
                    foreach ($model->tags as $tag) {
54
                        $labels[] = IpTag::widget(['tag' => $tag]);
55
                    }
56
                    return implode(' ', $labels);
57
                }
58
            ],
59
            'counters' => [
60
                'format' => 'html',
61
                'header' => Yii::t('hipanel/hosting', 'Counters'),
62
                'value' => function ($model) {
63
                    $html = '';
64
                    foreach ($model->objects_count as $count) {
65
                        if ($count['type'] === 'hdomain') {
66
                            $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...
67
                            $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...
68
                            $type = function ($count) {
69
                                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...
70
                            };
71
                        } else {
72
                            throw new InvalidParamException('The object type is not supported', $model);
73
                        }
74
75 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...
76
                            $html .= Html::a(
77
                                (int)$count['ok'] . '&nbsp;' . FontIcon::i('fa-check') . ' ' . $type($count['ok']),
78
                                $url['ok'],
79
                                ['class' => 'btn btn-success btn-xs']
80
                            );
81
                        }
82
                        $html .= ' ';
83 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...
84
                            $html .= Html::a(
85
                                (int)$count['deleted'] . '&nbsp;' . FontIcon::i('fa-trash') . ' ' . $type($count['deleted']),
86
                                $url['deleted'],
87
                                ['class' => 'btn btn-xs btn-warning']
88
                            );
89
                        }
90
                    }
91
92
                    return $html;
93
                }
94
            ],
95
            'links' => [
96
                'format' => 'html',
97
                'value' => function ($model) {
98
                    $items = [];
99
                    foreach ($model->links as $link) {
100
                        $item = Html::a($link->device, ['@server/view', 'id' => $link->device_id]);
101
                        if ($link->service_id) {
102
                            $item .= '&nbsp;' . FontIcon::i('fa-long-arrow-right');
103
                            $item .= '&nbsp;' . Html::a($link->service ?: $link->soft, ['@service/update', 'id' => $link->service_id]);
104
                        }
105
                        $items[] = $item;
106
                    }
107
                    return ArraySpoiler::widget(['data' => $items, 'visibleCount' => 3]);
108
                }
109
            ],
110
            'services' => [
111
                'attribute' => 'links',
112
                'format' => 'html',
113
                'label' => Yii::t('hipanel/server', 'Services'),
114
                'value' => function ($model) {
115
                    return ArraySpoiler::widget([
116
                        'data' => $model->links,
117
                        'formatter' => function ($link) {
118
                            if (Yii::$app->user->can('support') && Yii::getAlias('@service', false)) {
119
                                return Html::a($link->service, ['@service/view', 'id' => $link->service_id]);
120
                            }
121
122
                            return $link->service;
123
                        },
124
                    ]);
125
                },
126
            ],
127
            'actions' => [
128
                'class' => ActionColumn::class,
129
                'template' => '{view} {expand} {update} {delete}',
130
                'buttons' => [
131
                    'expand' => function ($url, $model) {
132
                        $options = array_merge([
133
                            'title' => Yii::t('hipanel/hosting', 'Expand'),
134
                            'aria-label' => Yii::t('hipanel/hosting', 'Expand'),
135
                            'data-pjax' => '0',
136
                            'data-id' => $model->id,
137
                            'class' => 'btn-expand-ip',
138
                        ]);
139
140
                        return Html::a(FontIcon::i('fa-th') . Yii::t('hipanel/hosting', 'Expand'), $url, $options);
141
                    },
142
                ],
143
            ],
144
            'ptr' => [
145
                'options' => [
146
                    'style' => 'width: 40%',
147
                ],
148
                'format' => 'raw',
149
                'value' => function ($model) {
150
                    if ($model->canSetPtr()) {
151
                        return XEditable::widget([
152
                            'model' => $model,
153
                            'attribute' => 'ptr',
154
                            'pluginOptions' => [
155
                                'url' => Url::to('@ip/set-ptr')
156
                            ],
157
                        ]);
158
                    }
159
160
                    return null;
161
                }
162
            ],
163
        ];
164
    }
165
}
166