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 — master ( c721cc...3ff35f )
by Ivan
09:59
created

BackendCategoryController   B

Complexity

Total Complexity 30

Size/Duplication

Total Lines 244
Duplicated Lines 18.85 %

Coupling/Cohesion

Components 1
Dependencies 18

Importance

Changes 0
Metric Value
wmc 30
lcom 1
cbo 18
dl 46
loc 244
rs 7.3333
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A behaviors() 14 14 1
A actionIndex() 23 23 2
D actionEdit() 9 96 17
B actionDelete() 0 22 4
A actionRemoveAll() 0 13 3
A actionAutocomplete() 0 22 2
B actions() 0 39 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
namespace app\modules\shop\controllers;
4
5
use app\backend\actions\PropertyHandler;
6
use app\backend\components\BackendController;
7
use app\backend\events\BackendEntityEditEvent;
8
use app\modules\image\widgets\views\AddImageAction;
9
use app\modules\shop\models\Category;
10
use app\models\Object;
11
use app\models\ViewObject;
12
use app\properties\HasProperties;
13
use app\modules\image\widgets\RemoveAction;
14
use app\modules\image\widgets\SaveInfoAction;
15
use app\modules\image\widgets\UploadAction;
16
use devgroup\JsTreeWidget\AdjacencyFullTreeDataAction;
17
use devgroup\JsTreeWidget\TreeNodeMoveAction;
18
use devgroup\JsTreeWidget\TreeNodesReorderAction;
19
use Yii;
20
use yii\db\Query;
21
use yii\filters\AccessControl;
22
use yii\helpers\Json;
23
use yii\helpers\Url;
24
use yii\web\NotFoundHttpException;
25
use yii\web\ServerErrorHttpException;
26
use app\modules\shop\actions\BatchEditPriceAction;
27
28
class BackendCategoryController extends BackendController
29
{
30
31
    const BACKEND_CATEGORY_EDIT = 'backend-category-edit';
32
    const BACKEND_CATEGORY_EDIT_SAVE = 'backend-category-edit-save';
33
    const BACKEND_CATEGORY_EDIT_FORM = 'backend-category-edit-form';
34
    const BACKEND_CATEGORY_AFTER_SAVE = 'backend-category-after-save';
35
36 View Code Duplication
    public function behaviors()
37
    {
38
        return [
39
            'access' => [
40
                'class' => AccessControl::className(),
41
                'rules' => [
42
                    [
43
                        'allow' => true,
44
                        'roles' => ['category manage'],
45
                    ],
46
                ],
47
            ],
48
        ];
49
    }
50
51
    public function actions()
52
    {
53
        return [
54
            'getTree' => [
55
                'class' => AdjacencyFullTreeDataAction::className(),
56
                'class_name' => Category::className(),
57
                'model_label_attribute' => 'name',
58
            ],
59
            'move' => [
60
                'class' => TreeNodeMoveAction::className(),
61
                'className' => Category::className(),
62
            ],
63
            'reorder' => [
64
                'class' => TreeNodesReorderAction::className(),
65
                'className' => Category::className(),
66
            ],
67
            'addImage' => [
68
                'class' => AddImageAction::className(),
69
            ],
70
            'upload' => [
71
                'class' => UploadAction::className(),
72
                'upload' => 'theme/resources/product-images',
73
            ],
74
            'remove' => [
75
                'class' => RemoveAction::className(),
76
                'uploadDir' => 'theme/resources/product-images',
77
            ],
78
            'save-info' => [
79
                'class' => SaveInfoAction::className(),
80
            ],
81
            'property-handler' => [
82
                'class' => PropertyHandler::className(),
83
                'modelName' => Category::className()
84
            ],
85
            'batch-edit-price' => [
86
                'class' => BatchEditPriceAction::className(),
87
            ]
88
        ];
89
    }
90
91 View Code Duplication
    public function actionIndex($parent_id = 0)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
92
    {
93
        $searchModel = new Category();
94
        $searchModel->parent_id = $parent_id;
95
96
        $params = Yii::$app->request->get();
97
98
        $dataProvider = $searchModel->search($params);
99
100
        $model = null;
101
        if ($parent_id > 0) {
102
            $model = Category::findOne($parent_id);
103
        }
104
105
        return $this->render(
106
            'index',
107
            [
108
                'dataProvider' => $dataProvider,
109
                'searchModel' => $searchModel,
110
                'model' => $model,
111
            ]
112
        );
113
    }
114
115
    public function actionEdit($parent_id = null, $id = null)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
116
    {
117
        if (null === $parent_id) {
118
            throw new NotFoundHttpException;
119
        }
120
121
        if (null === $object = Object::getForClass(Category::className())) {
122
            throw new ServerErrorHttpException;
123
        }
124
125
        /** @var null|Category|HasProperties $model */
126
        $model = null;
127
        if (null !== $id) {
128
            $model = Category::findById($id, null, null);
0 ignored issues
show
Unused Code introduced by
The call to Category::findById() has too many arguments starting with null.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
129
        } else {
130
            $parent = Category::findById($parent_id, null, null);
0 ignored issues
show
Unused Code introduced by
The call to Category::findById() has too many arguments starting with null.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
131
            if ($parent_id === '0' || !is_null($parent)) {
132
                $model = new Category;
133
                $model->loadDefaultValues();
134
                $model->parent_id = $parent_id;
135
                if ($parent_id !== '0') {
136
                    $model->category_group_id = $parent->category_group_id;
137
                }
138
            } else {
139
                throw new ServerErrorHttpException;
140
            }
141
        }
142
143
        if (null === $model) {
144
            throw new ServerErrorHttpException;
145
        }
146
147
        $event = new BackendEntityEditEvent($model);
148
        $this->trigger(self::BACKEND_CATEGORY_EDIT, $event);
149
150
        $post = \Yii::$app->request->post();
151
        if ($event->isValid && $model->load($post) && $model->validate()) {
152
            $saveStateEvent = new BackendEntityEditEvent($model);
153
            $this->trigger(self::BACKEND_CATEGORY_EDIT_SAVE, $saveStateEvent);
154
155
            $save_result = $model->save();
156
            $model->saveProperties($post);
0 ignored issues
show
Documentation Bug introduced by
The method saveProperties does not exist on object<app\modules\shop\models\Category>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
157
158 View Code Duplication
            if (null !== $view_object = ViewObject::getByModel($model, true)) {
159
                if ($view_object->load($post, 'ViewObject')) {
160
                    if ($view_object->view_id <= 0) {
161
                        $view_object->delete();
162
                    } else {
163
                        $view_object->save();
164
                    }
165
                }
166
            }
167
168
            if ($save_result) {
169
                $modelAfterSaveEvent = new BackendEntityEditEvent($model);
170
                $this->trigger(self::BACKEND_CATEGORY_AFTER_SAVE, $modelAfterSaveEvent);
171
172
                $this->runAction('save-info', ['model_id'=>$model->id]);
173
                Yii::$app->session->setFlash('success', Yii::t('app', 'Record has been saved'));
174
                $returnUrl = Yii::$app->request->get('returnUrl', ['index']);
175
                switch (Yii::$app->request->post('action', 'save')) {
176
                    case 'next':
177
                        return $this->redirect(
178
                            [
179
                                'edit',
180
                                'returnUrl' => $returnUrl,
181
                                'parent_id' => Yii::$app->request->get('parent_id', null)
182
                            ]
183
                        );
184
                    case 'back':
185
                        return $this->redirect($returnUrl);
186
                    default:
187
                        return $this->redirect(
188
                            Url::toRoute(
189
                                [
190
                                    'edit',
191
                                    'id' => $model->id,
192
                                    'returnUrl' => $returnUrl,
193
                                    'parent_id' => $model->parent_id
194
                                ]
195
                            )
196
                        );
197
                }
198
            } else {
199
                throw new ServerErrorHttpException;
200
            }
201
        }
202
203
        return $this->render(
204
            'category-form',
205
            [
206
                'model' => $model,
207
                'object' => $object,
208
            ]
209
        );
210
    }
211
212
    public function actionDelete($id = null, $parent_id = null, $mode = null)
0 ignored issues
show
Unused Code introduced by
The parameter $parent_id 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...
213
    {
214
215
        if ((null === $id) || (null === $model = Category::findById($id, null, null))) {
0 ignored issues
show
Unused Code introduced by
The call to Category::findById() has too many arguments starting with null.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
216
            throw new NotFoundHttpException;
217
        }
218
219
        $model->deleteMode = $mode;
220
        if (!$model->delete()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $model->delete() of type false|integer is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
221
            Yii::$app->session->setFlash('success', Yii::t('app', 'The object is placed in the cart'));
222
        } else {
223
            Yii::$app->session->setFlash('success', Yii::t('app', 'Object has been removed'));
224
        }
225
226
        return $this->redirect(
227
            Yii::$app->request->get(
228
                'returnUrl',
229
                Url::to(['index', 'parent_id' => $model->parent_id])
230
            )
231
        );
232
233
    }
234
235
    public function actionRemoveAll($parent_id, $mode = null)
236
    {
237
        $items = Yii::$app->request->post('items', []);
238
        if (!empty($items)) {
239
            $items = Category::findAll(['id' => $items]);
240
            /** @var Category[] $items */
241
            foreach ($items as $item) {
242
                $item->deleteMode = $mode;
243
                $item->delete();
244
            }
245
        }
246
        return $this->redirect(['index', 'parent_id' => $parent_id]);
247
    }
248
249
    public function actionAutocomplete()
250
    {
251
        /**
252
         * @todo Добавить отображение вложенности
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
253
         */
254
        $search = Yii::$app->request->get('search');
255
        $out = ['more' => false];
256
        if (!is_null($search['term'])) {
257
            $query = new Query;
258
            $query->select('id, name AS text')->from(Category::tableName())->andWhere(['like', 'name', $search['term']])->limit(
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 128 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...
259
                100
260
            );
261
            $command = $query->createCommand();
262
            $data = $command->queryAll();
263
            $out['results'] = array_values($data);
264
        }/* elseif ($id > 0) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
265
            $out['results'] = ['id' => $id, 'text' => Category::findOne($id)->name];
266
        } else {
267
            $out['results'] = ['id' => 0, 'text' => Yii::t('app', 'No matching records found')];
268
        }*/
269
        echo Json::encode($out);
270
    }
271
}
272