GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Push — filters-dev ( b8c330...c59b06 )
by Ivan
11:21
created

AddonsController   B

Complexity

Total Complexity 36

Size/Duplication

Total Lines 314
Duplicated Lines 15.29 %

Coupling/Cohesion

Components 1
Dependencies 7
Metric Value
wmc 36
lcom 1
cbo 7
dl 48
loc 314
rs 8.8

9 Methods

Rating   Name   Duplication   Size   Complexity  
A actionEditCategory() 16 16 4
A behaviors() 14 14 1
A actions() 0 21 1
A actionIndex() 0 15 1
A actionViewCategory() 18 18 1
C actionEditAddon() 0 29 8
B actionAjaxSearchAddons() 0 28 2
B actionReorder() 0 61 8
C actionAddAddonBinding() 0 69 10

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
namespace app\modules\shop\backend;
4
5
use app\backend\components\BackendController;
6
use app\models\Object;
7
use app\modules\shop\models\Addon;
8
use app\modules\shop\models\AddonBindings;
9
use app\modules\shop\models\Currency;
10
use app\modules\shop\widgets\AddonsListWidget;
11
use app\traits\LoadModel;
12
use app\backend\traits\BackendRedirect;
13
use app\backend\actions\MultipleDelete;
14
use app\backend\actions\DeleteOne;
15
use app\modules\shop\models\AddonCategory;
16
use Yii;
17
use yii\caching\TagDependency;
18
use yii\filters\AccessControl;
19
use yii\helpers\Html;
20
use yii\helpers\Url;
21
use yii\web\BadRequestHttpException;
22
use yii\web\NotFoundHttpException;
23
use yii\web\Response;
24
25
/**
26
 * Backend controller for managing addons, their categories and bindings
27
 * @package app\modules\shop\backend\
28
 */
29
class AddonsController extends BackendController
30
{
31
    use BackendRedirect;
32
    use LoadModel;
33
    /**
34
     * @inheritdoc
35
     * @return array
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use array<string,array>.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
36
     */
37 View Code Duplication
    public function behaviors()
38
    {
39
        return [
40
            'access' => [
41
                'class' => AccessControl::className(),
42
                'rules' => [
43
                    [
44
                        'allow' => true,
45
                        'roles' => ['product manage'],
46
                    ],
47
                ],
48
            ],
49
        ];
50
    }
51
52
    /**
53
     * @inheritdoc
54
     */
55
    public function actions()
56
    {
57
        return [
58
            'remove-all-categories' => [
59
                'class' => MultipleDelete::className(),
60
                'modelName' => AddonCategory::className(),
61
            ],
62
            'delete-category' => [
63
                'class' => DeleteOne::className(),
64
                'modelName' => AddonCategory::className(),
65
            ],
66
            'remove-all-addons' => [
67
                'class' => MultipleDelete::className(),
68
                'modelName' => Addon::className(),
69
            ],
70
            'delete-addon' => [
71
                'class' => DeleteOne::className(),
72
                'modelName' => Addon::className(),
73
            ],
74
        ];
75
    }
76
77
    /**
78
     * Renders AddonCategory grid
79
     * @return string
80
     */
81
    public function actionIndex()
82
    {
83
        $searchModel = new AddonCategory();
84
        $params = Yii::$app->request->get();
85
86
        $dataProvider = $searchModel->search($params);
87
88
        return $this->render(
89
            'index',
90
            [
91
                'searchModel' => $searchModel,
92
                'dataProvider' => $dataProvider,
93
            ]
94
        );
95
    }
96
97
    /**
98
     * Add or edit existing AddonCategory model
99
     * @param null|string $id
100
     * @return string|\yii\web\Response
101
     * @throws NotFoundHttpException
102
     */
103 View Code Duplication
    public function actionEditCategory($id=null)
104
    {
105
        $model = $this->loadModel(AddonCategory::className(), $id, true);
106
107
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
108
            if ($model->save()) {
109
                return $this->redirectUser($model->id, true, 'index', 'edit-category');
110
            }
111
        }
112
        return $this->render(
113
            'edit-category',
114
            [
115
                'model' => $model,
116
            ]
117
        );
118
    }
119
120
    /**
121
     * Shows list of Addons binded to specified AddonCategory
122
     * @param $id
123
     * @return string
124
     * @throws NotFoundHttpException
125
     */
126 View Code Duplication
    public function actionViewCategory($id)
127
    {
128
        /** @var AddonCategory $addonCategory */
129
        $addonCategory = $this->loadModel(AddonCategory::className(), $id);
130
        $searchModel = new Addon();
131
        $params = Yii::$app->request->get();
132
133
        $dataProvider = $searchModel->search($params, $addonCategory->id);
134
135
        return $this->render(
136
            'addons-list',
137
            [
138
                'searchModel' => $searchModel,
139
                'dataProvider' => $dataProvider,
140
                'addonCategory' => $addonCategory,
141
            ]
142
        );
143
    }
144
145
    /**
146
     * Add or edit existing Addon model
147
     * @param string|int $addon_category_id
0 ignored issues
show
Documentation introduced by
Should the type for parameter $addon_category_id not be string|integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
148
     * @param null|string $id
149
     * @return string|\yii\web\Response
150
     * @throws NotFoundHttpException
151
     */
152
    public function actionEditAddon($addon_category_id=null, $id=null)
0 ignored issues
show
Coding Style introduced by
actionEditAddon uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
153
    {
154
        if ($addon_category_id === null && $id===null) {
155
            if (isset($_POST['addon_category_id'])) {
156
                $addon_category_id = intval($_POST['addon_category_id']);
157
            }
158
        }
159
160
        $addonCategory = $this->loadModel(AddonCategory::className(), $addon_category_id);
161
        /** @var Addon $model */
162
        $model = $this->loadModel(Addon::className(), $id, true);
163
        if ($id === null) {
164
            $model->loadDefaultValues();
165
            $model->addon_category_id = $addon_category_id;
166
        }
167
168
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
169
            if ($model->save()) {
170
                return $this->redirectUser($model->id, true, 'view-category', 'edit-addon',['addon_category_id'=>$addon_category_id]);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 134 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
171
            }
172
        }
173
        return $this->render(
174
            'edit-addon',
175
            [
176
                'model' => $model,
177
                'addonCategory' => $addonCategory,
178
            ]
179
        );
180
    }
181
182
    public function actionAjaxSearchAddons()
183
    {
184
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
185
186
        $result = [
187
            'more' => false,
188
            'results' => []
189
        ];
190
        $search = Yii::$app->request->get('search');
191
        if (!empty($search['term'])) {
192
            $query = new \yii\db\Query();
193
            $query->select('id, name as text, price, currency_id')->from(Addon::tableName())->andWhere(
194
                ['like', 'name', $search['term']]
195
            )->orderBy(['name' => SORT_ASC]);
196
            $command = $query->createCommand();
197
            $data = $command->queryAll();
198
            $data = array_map(function($item) {
199
                $currency = Currency::findById($item['currency_id']);
200
                $price = $currency->format($item['price']);
201
                $item['text'] .= ' - ' . $price;
202
                return $item;
203
            }, $data);
204
205
            $result['results'] = array_values($data);
206
        }
207
208
        return $result;
209
    }
210
211
    public function actionReorder()
212
    {
213
        if (Yii::$app->request->isAjax === false) {
214
            throw new BadRequestHttpException;
215
        }
216
        Yii::$app->response->format = Response::FORMAT_JSON;
217
218
219
        $object_id = Yii::$app->request->get('object_id', null);
220
        $object_model_id = Yii::$app->request->get('object_model_id', null);
221
        $addons = (array) Yii::$app->request->post('addons', []);
222
223
        if ($object_id === null || $object_model_id === null || empty($addons)){
224
            throw new BadRequestHttpException;
225
        }
226
227
        array_walk($addons, function($item){
228
            return intval($item);
229
        });
230
        // magic begins
231
        $priorities=[];
232
        $start=0;
233
        $ids_sorted = $addons;
234
        sort($ids_sorted);
235
        foreach ($addons as $id) {
236
            $priorities[$id] = $start++;
237
        }
238
        $result = 'CASE addons.`id`';
239
        foreach ($priorities as $k => $v) {
240
            $result .= ' when "' . $k . '" then "' . $v . '"';
241
        }
242
        $case = $result . ' END';
243
244
        $query = <<< SQL
245
UPDATE {{%addon_bindings}} ab
246
INNER JOIN {{%addon}} addons ON addons.id = ab.addon_id
247
SET ab.`sort_order` = $case
248
SQL;
249
        $query .= ' where addons.id IN ('.implode(', ', $addons).')';
250
251
        Yii::$app->db->createCommand($query)->execute();
252
253
        TagDependency::invalidate(Yii::$app->cache, [Addon::className()]);
254
255
        $object = Object::findById($object_id);
256
        if ($object === null) {
257
            throw new NotFoundHttpException;
258
        }
259
        $modelClassName = $object->object_class;
260
        $model = $this->loadModel($modelClassName, $object_model_id);
261
262
        return [
263
            'query' => $query,
264
            'data' => AddonsListWidget::widget([
265
                'object_id' => $object->id,
266
                'object_model_id' => $model->id,
267
                'bindedAddons' => $model->bindedAddons,
268
            ]),
269
            'error' => false,
270
        ];
271
    }
272
273
    public function actionAddAddonBinding($remove='0')
274
    {
275
        if (Yii::$app->request->isAjax === false) {
276
            throw new BadRequestHttpException;
277
        }
278
        Yii::$app->response->format = Response::FORMAT_JSON;
279
280
        $addon_id = Yii::$app->request->post('addon_id', null);
281
        $object_id = Yii::$app->request->get('object_id', null);
282
        $object_model_id = Yii::$app->request->get('object_model_id', null);
283
        if ($addon_id === null || $object_id === null || $object_model_id === null){
284
            throw new BadRequestHttpException;
285
        }
286
287
288
        $addon = Addon::findById($addon_id);
289
        $object = Object::findById($object_id);
290
        if ($addon === null || $object === null) {
291
            throw new NotFoundHttpException;
292
        }
293
        $modelClassName = $object->object_class;
294
        $model = $this->loadModel($modelClassName, $object_model_id);
295
296
297
        // ok, now all's ok, addon and model exist!
298
        try {
299
300
            if ($remove==='1') {
301
                $model->unlink('bindedAddons', $addon, true);
302
            } else {
303
                $model->link(
304
                    'bindedAddons',
305
                    $addon,
306
                    [
307
                        'sort_order' => count($model->bindedAddons),
308
                        'appliance_object_id' => $object->id,
309
                    ]
310
                );
311
            }
312
313
        } catch (\Exception $e) {
314
            if ( intval($e->getCode())  == 23000) {
315
                return [
316
                    'data' =>
317
                        Html::tag('div', Yii::t('app', 'Addon is already added'), ['class' => 'alert alert-info']) .
318
                        AddonsListWidget::widget([
319
                            'object_id' => $object->id,
320
                            'object_model_id' => $model->id,
321
                            'bindedAddons' => $model->bindedAddons,
322
                        ]),
323
                    'error' => false,
324
                ];
325
            } else {
326
                return [
327
                    'data' => Html::tag('div', $e->getMessage(), ['class' => 'alert alert-danger']),
328
                    'error' => $e->getMessage()
329
                ];
330
            }
331
        }
332
        TagDependency::invalidate(Yii::$app->cache, [Addon::className()]);
333
        return [
334
            'data' => AddonsListWidget::widget([
335
                'object_id' => $object->id,
336
                'object_model_id' => $model->id,
337
                'bindedAddons' => $model->bindedAddons,
338
            ]),
339
            'error' => false,
340
        ];
341
    }
342
}
343