IpController   A
last analyzed

Complexity

Total Complexity 26

Size/Duplication

Total Lines 200
Duplicated Lines 7 %

Coupling/Cohesion

Components 1
Dependencies 12

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 26
lcom 1
cbo 12
dl 14
loc 200
ccs 0
cts 169
cp 0
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A behaviors() 14 14 1
C actions() 0 111 12
A getIpTags() 0 4 1
A actionExpand() 0 13 3
B collectionLoader() 0 31 8
A getDataProviderOptions() 0 16 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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-2019, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hipanel\modules\hosting\controllers;
12
13
use hipanel\actions\IndexAction;
14
use hipanel\actions\SearchAction;
15
use hipanel\actions\SmartCreateAction;
16
use hipanel\actions\SmartDeleteAction;
17
use hipanel\actions\SmartUpdateAction;
18
use hipanel\actions\ValidateFormAction;
19
use hipanel\actions\ViewAction;
20
use hipanel\filters\EasyAccessControl;
21
use hipanel\modules\hosting\models\Ip;
22
use hipanel\modules\hosting\models\Link;
23
use hiqdev\hiart\Collection;
24
use hiqdev\hiart\ResponseErrorException;
25
use Yii;
26
use yii\base\Event;
27
use yii\helpers\ArrayHelper;
28
29
class IpController extends \hipanel\base\CrudController
30
{
31 View Code Duplication
    public function behaviors()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
32
    {
33
        return ArrayHelper::merge(parent::behaviors(), [
34
            [
35
                'class' => EasyAccessControl::class,
36
                'actions' => [
37
                    'create' => 'admin',
38
                    'update' => 'admin',
39
                    'delete' => 'admin',
40
                    '*' => 'server.read',
41
                ],
42
            ],
43
        ]);
44
    }
45
46
    public function actions()
47
    {
48
        return array_merge(parent::actions(), [
49
            'index' => [
50
                'class' => IndexAction::class,
51
                'on beforePerform' => $this->getDataProviderOptions(),
52
                'data' => function ($action) {
53
                    return [
54
                        'ipTags' => $action->controller->getIpTags(),
55
                    ];
56
                },
57
            ],
58
            'search-service-edit' => [
59
                'class' => SearchAction::class,
60
                'on beforePerform' => $this->getDataProviderOptions(),
61
                'ajaxResponseFormatter' => function ($action) {
62
                    /** @var SearchAction $action */
63
                    $data = [];
64
                    $results = [];
65
66
                    foreach ($action->collection->models as $k => $v) {
67
                        $data[$k] = ArrayHelper::toArray($v, $action->parent->getReturnOptions());
68
                    }
69
70
                    $device = Yii::$app->request->post('server');
71
72
                    foreach ($data as $item) {
73
                        if ($device && $item['links']) {
74
                            foreach ($item['links'] as $link) {
75
                                if ($link['device'] === $device) {
76
                                    $results[] = ArrayHelper::merge($item, [
77
                                        'service' => $link['service'],
78
                                        'device' => $link['device'],
79
                                    ]);
80
                                }
81
                            }
82
                        } else {
83
                            $results[] = $item;
84
                        }
85
                    }
86
87
                    return $results;
88
                },
89
            ],
90
            'view' => [
91
                'class' => ViewAction::class,
92
                'on beforePerform' => $this->getDataProviderOptions(),
93
            ],
94
            'create' => [
95
                'class' => SmartCreateAction::class,
96
                'success' => Yii::t('hipanel:hosting', 'IP address was created successfully'),
97
                'error' => Yii::t('hipanel:hosting', 'An error occurred when trying to create an IP address'),
98
                'data' => function ($action, $data) {
99
                    /** @var Ip $model */
100
                    foreach ($data['models'] as $model) {
101
                        if (empty($model->getAddedLinks())) {
102
                            $model->addLink(new Link(['scenario' => 'create']));
103
                        }
104
                    }
105
106
                    return [
107
                        'tags' => $this->getIpTags(),
108
                    ];
109
                },
110
                'collectionLoader' => function ($action, $data) {
0 ignored issues
show
Unused Code introduced by
The parameter $data is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
111
                    $this->collectionLoader($action->scenario, $action->collection);
112
                },
113
            ],
114
            'update' => [
115
                'class' => SmartUpdateAction::class,
116
                'success' => Yii::t('hipanel:hosting', 'IP address was updated successfully'),
117
                'error' => Yii::t('hipanel:hosting', 'An error occurred when trying to update an IP address'),
118
                'data' => function ($action, $data = []) {
119
                    /** @var Ip $model */
120
                    foreach ($data['models'] as $model) {
121
                        if (empty($model->getAddedLinks())) {
122
                            if (empty($model->links)) {
123
                                $model->addLink(new Link(['scenario' => 'create']));
124
                            } else {
125
                                $model->setAddedLinks($model->links);
126
                            }
127
                        }
128
                    }
129
130
                    return [
131
                        'tags' => $this->getIpTags(),
132
                    ];
133
                },
134
                'collectionLoader' => function ($action, $data) {
0 ignored issues
show
Unused Code introduced by
The parameter $data is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
135
                    $this->collectionLoader($action->scenario, $action->collection);
136
                },
137
                'on beforeFetch' => $this->getDataProviderOptions(),
138
            ],
139
            'delete' => [
140
                'class' => SmartDeleteAction::class,
141
                'success' => Yii::t('hipanel:hosting', 'IP address was deleted successfully'),
142
            ],
143
            'validate-form' => [
144
                'class' => ValidateFormAction::class,
145
            ],
146
            'set-ptr' => [
147
                'class' => SmartUpdateAction::class,
148
                'scenario' => 'set-ptr',
149
            ],
150
            'set-note' => [
151
                'class' => SmartUpdateAction::class,
152
                'success' => Yii::t('hipanel:hosting', 'Note changed'),
153
                'error' => Yii::t('hipanel:hosting', 'Failed to change note'),
154
            ],
155
        ]);
156
    }
157
158
    public function getIpTags()
159
    {
160
        return $this->getRefs('tag,ip', 'hipanel:hosting');
161
    }
162
163
    public function actionExpand($id)
164
    {
165
        try {
166
            $ips = Ip::perform('expand', ['id' => $id, 'with_existing' => true]);
167
        } catch (ResponseErrorException $e) {
168
            if ($e->getMessage() === 'result is too long') {
169
                return Yii::t('hipanel:hosting', 'Too many IP addresses in the network');
170
            }
171
            throw $e;
172
        }
173
174
        return $this->renderAjax('expand', ['ips' => $ips]);
175
    }
176
177
    public function collectionLoader($scenario, Collection $collection)
178
    {
179
        $ipModel = $this->newModel(['scenario' => $scenario]);
180
        $linkModel = new Link(['scenario' => $scenario]);
181
182
        $ipModels = [$ipModel];
183
        for ($i = 1; $i < count(Yii::$app->request->post($ipModel->formName(), [])); ++$i) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
184
            $ipModels[] = clone $ipModel;
185
        }
186
187
        if (Ip::loadMultiple($ipModels, Yii::$app->request->post())) {
188
            /** @var Ip $ip */
189
            foreach ($ipModels as $i => $ip) {
190
                $ipLinkModels = [$linkModel];
191
                $ipLinks = ArrayHelper::getValue(Yii::$app->request->post($linkModel->formName(), []), $i, []);
192
                for ($i = 1; $i < count($ipLinks); ++$i) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
193
                    $ipLinkModels[] = clone $linkModel;
194
                }
195
                Link::loadMultiple($ipLinkModels, [$linkModel->formName() => $ipLinks]);
196
197
                /** @var Link $link */
198
                foreach ($ipLinkModels as $link) {
199
                    if ($link->ip_id === $ip->id && $link->validate()) {
0 ignored issues
show
Documentation introduced by
The property ip_id does not exist on object<hipanel\modules\hosting\models\Link>. 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...
200
                        $ip->addLink($link);
201
                    }
202
                }
203
            }
204
205
            $collection->set($ipModels);
206
        }
207
    }
208
209
    /**
210
     * @return \Closure
211
     */
212
    public function getDataProviderOptions()
213
    {
214
        return function (Event $event) {
215
            /** @var \hipanel\actions\SearchAction $action */
216
            $action = $event->sender;
217
            $dataProvider = $action->getDataProvider();
218
            $dataProvider->query->joinWith('links');
219
220
            // TODO: ipModule is not wise yet. Redo
221
            $dataProvider->query
222
                ->andWhere(['with_links' => 1])
223
                ->andWhere(['with_tags' => 1])
224
                ->andWhere(['with_ptr' => 1])
225
                ->andWhere(['with_counters' => 1]);
226
        };
227
    }
228
}
229