Completed
Push — master ( 692da5...8a82b5 )
by Dmitry
05:31
created

IpController::actions()   C

Complexity

Conditions 12
Paths 1

Size

Total Lines 112
Code Lines 70

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 156

Importance

Changes 13
Bugs 0 Features 2
Metric Value
c 13
b 0
f 2
dl 0
loc 112
ccs 0
cts 97
cp 0
rs 5.034
cc 12
eloc 70
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
/**
13
 * @link    http://hiqdev.com/hipanel-module-hosting
14
 * @license http://hiqdev.com/hipanel-module-hosting/license
15
 * @copyright Copyright (c) 2015 HiQDev
16
 */
17
18
namespace hipanel\modules\hosting\controllers;
19
20
use hipanel\actions\IndexAction;
21
use hipanel\actions\OrientationAction;
22
use hipanel\actions\SearchAction;
23
use hipanel\actions\SmartCreateAction;
24
use hipanel\actions\SmartDeleteAction;
25
use hipanel\actions\SmartUpdateAction;
26
use hipanel\actions\ValidateFormAction;
27
use hipanel\actions\ViewAction;
28
use hipanel\modules\hosting\models\Ip;
29
use hipanel\modules\hosting\models\Link;
30
use hiqdev\hiart\Collection;
31
use hiqdev\hiart\ErrorResponseException;
32
use Yii;
33
use yii\base\Event;
34
use yii\filters\AccessControl;
35
use yii\helpers\ArrayHelper;
36
37
class IpController extends \hipanel\base\CrudController
38
{
39 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...
40
    {
41
        return ArrayHelper::merge(parent::behaviors(), [
42
            'manage-access' => [
43
                'class' => AccessControl::class,
44
                'only'  => ['create', 'update', 'delete'],
45
                'rules' => [
46
                    [
47
                        'allow'   => true,
48
                        'roles'   => ['admin'],
49
                    ],
50
                ],
51
            ],
52
        ]);
53
    }
54
55
    public function actions()
56
    {
57
        return [
58
            'set-orientation' => [
59
                'class' => OrientationAction::class,
60
                'allowedRoutes' => [
61
                    '/hosting/ip/index'
62
                ]
63
            ],
64
            'index' => [
65
                'class' => IndexAction::class,
66
                'on beforePerform' => $this->getDataProviderOptions(),
67
                'data' => function ($action) {
68
                    return [
69
                        'ipTags' => $action->controller->getIpTags()
70
                    ];
71
                }
72
            ],
73
            'search-service-edit' => [
74
                'class' => SearchAction::class,
75
                'on beforePerform' => $this->getDataProviderOptions(),
76
                'ajaxResponseFormatter' => function ($action) {
77
                    /** @var SearchAction $action */
78
                    $data = [];
79
                    $results = [];
80
81
                    foreach ($action->collection->models as $k => $v) {
82
                        $data[$k] = ArrayHelper::toArray($v, $action->parent->getReturnOptions());
83
                    }
84
85
                    $device = Yii::$app->request->post('server');
86
87
                    foreach ($data as $item) {
88
                        if ($device && $item['links']) {
89
                            foreach ($item['links'] as $link) {
90
                                if ($link['device'] === $device) {
91
                                    $results[] = ArrayHelper::merge($item, [
92
                                        'service' => $link['service'],
93
                                        'device' => $link['device'],
94
                                    ]);
95
                                }
96
                            }
97
                        } else {
98
                            $results[] = $item;
99
                        }
100
                    }
101
102
                    return $results;
103
                }
104
            ],
105
            'view' => [
106
                'class' => ViewAction::class,
107
                'on beforePerform' => $this->getDataProviderOptions(),
108
            ],
109
            'create' => [
110
                'class' => SmartCreateAction::class,
111
                'success' => Yii::t('hipanel/hosting', 'IP address was created successfully'),
112
                'error' => Yii::t('hipanel/hosting', 'An error occurred when trying to create an IP address'),
113
                'data' => function ($action, $data) {
114
                    /** @var Ip $model */
115
                    foreach ($data['models'] as $model) {
116
                        if (empty($model->getAddedLinks())) {
117
                            $model->addLink(new Link(['scenario' => 'create']));
118
                        }
119
                    }
120
121
                    return [
122
                        'tags' => $this->getIpTags()
123
                    ];
124
                },
125
                '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...
126
                    $this->collectionLoader($action->scenario, $action->collection);
127
                },
128
            ],
129
            'update' => [
130
                'class' => SmartUpdateAction::class,
131
                'success' => Yii::t('hipanel/hosting', 'IP address was updated successfully'),
132
                'error' => Yii::t('hipanel/hosting', 'An error occurred when trying to update an IP address'),
133
                'data' => function ($action, $data = []) {
134
                    /** @var Ip $model */
135
                    foreach ($data['models'] as $model) {
136
                        if (empty($model->getAddedLinks())) {
137
                            if (empty($model->links)) {
138
                                $model->addLink(new Link(['scenario' => 'create']));
139
                            } else {
140
                                $model->setAddedLinks($model->links);
141
                            }
142
                        }
143
                    }
144
145
                    return [
146
                        'tags' => $this->getIpTags()
147
                    ];
148
                },
149
                '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...
150
                    $this->collectionLoader($action->scenario, $action->collection);
151
                },
152
                'on beforeFetch' => $this->getDataProviderOptions(),
153
            ],
154
            'delete' => [
155
                'class' => SmartDeleteAction::class,
156
                'success' => Yii::t('hipanel/hosting', 'IP address was deleted successfully')
157
            ],
158
            'validate-form' => [
159
                'class' => ValidateFormAction::class,
160
            ],
161
            'set-ptr' => [
162
                'class' => SmartUpdateAction::class,
163
                'scenario' => 'set-ptr',
164
            ]
165
        ];
166
    }
167
168
    public function getIpTags()
169
    {
170
        return $this->getRefs('tag,ip', 'hipanel/hosting');
171
    }
172
173
    public function actionExpand($id)
174
    {
175
        try {
176
            $ips = Ip::perform('Expand', ['id' => $id, 'with_existing' => true]);
177
        } catch (ErrorResponseException $e) {
178
            if ($e->getMessage() === 'result is too long') {
179
                return Yii::t('hipanel/hosting', 'Too many IP addresses in the network');
180
            }
181
            throw $e;
182
        }
183
        return $this->renderAjax('expand', ['ips' => $ips]);
184
    }
185
186
    public function collectionLoader($scenario, Collection $collection)
187
    {
188
        $ipModel = $this->newModel(['scenario' => $scenario]);
189
        $linkModel = new Link(['scenario' => $scenario]);
190
191
        $ipModels = [$ipModel];
192
        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...
193
            $ipModels[] = clone $ipModel;
194
        }
195
196
        if (Ip::loadMultiple($ipModels, Yii::$app->request->post())) {
197
            /** @var Ip $ip */
198
            foreach ($ipModels as $i => $ip) {
199
                $ipLinkModels = [$linkModel];
200
                $ipLinks = ArrayHelper::getValue(Yii::$app->request->post($linkModel->formName(), []), $i, []);
201
                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...
202
                    $ipLinkModels[] = clone $linkModel;
203
                }
204
                Link::loadMultiple($ipLinkModels, [$linkModel->formName() => $ipLinks]);
205
206
                /** @var Link $link */
207
                foreach ($ipLinkModels as $link) {
208
                    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...
209
                        $ip->addLink($link);
210
                    }
211
                }
212
            }
213
214
            $collection->set($ipModels);
215
        }
216
    }
217
218
    /**
219
     * @return \Closure
220
     */
221
    public function getDataProviderOptions()
222
    {
223
        return function (Event $event) {
224
            /** @var \hipanel\actions\SearchAction $action */
225
            $action = $event->sender;
226
            $dataProvider = $action->getDataProvider();
227
            $dataProvider->query->joinWith('links');
228
            $dataProvider->query->joinWith('ptr');
229
230
            // TODO: ipModule is not wise yet. Redo
231
            $dataProvider->query
232
                ->andWhere(['with_links' => 1])
233
                ->andWhere(['with_tags' => 1])
234
                ->andWhere(['with_ptr' => 1])
235
                ->andWhere(['with_counters' => 1]);
236
        };
237
    }
238
}
239