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

BackendReviewController   B

Complexity

Total Complexity 45

Size/Duplication

Total Lines 317
Duplicated Lines 8.2 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 45
c 1
b 0
f 0
lcom 1
cbo 5
dl 26
loc 317
rs 8.3673

11 Methods

Rating   Name   Duplication   Size   Complexity  
A actionIndex() 0 22 1
A actionDelete() 0 13 4
A behaviors() 14 14 1
B actionView() 5 20 5
B actionUpdateStatus() 0 33 5
B actionMarkSpam() 0 33 6
A actionRemoveAll() 0 12 3
A loadModel() 0 8 2
B actionCreate() 7 32 6
C actionAjaxSearch() 0 59 9
B actionAjaxGetTree() 0 27 3

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like BackendReviewController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use BackendReviewController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace app\modules\review\controllers;
4
5
use app\models\Object;
6
use app\modules\page\models\Page;
7
use app\modules\review\models\Review;
8
use app\modules\shop\models\Category;
9
use app\modules\shop\models\Product;
10
use yii\db\ActiveRecord;
11
use yii\filters\AccessControl;
12
use yii\helpers\Url;
13
use yii\web\BadRequestHttpException;
14
use Yii;
15
use yii\web\NotFoundHttpException;
16
use app\components\SearchModel;
17
use app\models\Submission;
18
use yii\web\Response;
19
20
class BackendReviewController extends \app\backend\components\BackendController
21
{
22
23
    const BACKEND_REVIEW_EDIT = 'backend-review-edit';
24
    const BACKEND_REVIEW_EDIT_SAVE = 'backend-review-edit-save';
25
    const BACKEND_REVIEW_EDIT_FORM = 'backend-review-edit-form';
26
    const BACKEND_REVIEW_AFTER_SAVE = 'backend-review-after-save';
27
28
29 View Code Duplication
    public function behaviors()
30
    {
31
        return [
32
            'access' => [
33
                'class' => AccessControl::className(),
34
                'rules' => [
35
                    [
36
                        'allow' => true,
37
                        'roles' => ['review manage'],
38
                    ],
39
                ],
40
            ],
41
        ];
42
    }
43
44
    public function actionIndex()
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...
45
    {
46
        $searchModelConfig = [
47
            'defaultOrder' => ['id' => SORT_DESC],
48
            'model' => Review::className(),
49
            'relations' => [
50
                'submission.form' => ['name'],
51
            ],
52
            'additionalConditions' => [
53
                ['parent_id' => 0],
54
            ]
55
        ];
56
        $searchModel = new SearchModel($searchModelConfig);
57
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
58
        return $this->render(
59
            'index',
60
            [
61
                'dataProvider' => $dataProvider,
62
                'searchModel' => $searchModel,
63
            ]
64
        );
65
    }
66
67
    public function actionView($id)
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...
68
    {
69
        $model = Review::find()
70
            ->with(['submission'])
71
            ->where(['id' => $id])
72
            ->one();
73
        if (null === $model) {
74
            throw new NotFoundHttpException;
75
        }
76
77 View Code Duplication
        if (true === Yii::$app->request->isPost) {
78
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
79
                return $this->redirect(Url::toRoute(['view', 'id' => $model->id]));
80
            }
81
        }
82
83
        return $this->render('edit', [
84
            'review' => $model
85
        ]);
86
    }
87
88
    public function actionUpdateStatus($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...
89
    {
90
        if (null === $id) {
91
            $id = \Yii::$app->request->post('editableKey');
92
            $index = \Yii::$app->request->post('editableIndex');
93
            if (null === $id || null === $index) {
94
                throw new BadRequestHttpException;
95
            } else {
96
                $review = $this->loadModel($id);
97
                $reviews = \Yii::$app->request->post('Review', []);
98
                $review->status = $reviews[$index]['status'];
99
                return $review->update();
100
            }
101
        } else {
102
            $reviews = $reviews = \Yii::$app->request->post('Review');
103
            $status = $reviews['status'];
104
            $review = $this->loadModel($id);
105
            $review->status = $status;
106
            if ($review->update()) {
107
                Yii::$app->session->setFlash('success', Yii::t('app', 'Review successfully updated'));
108
            } else {
109
                Yii::$app->session->setFlash('error', Yii::t('app', 'Error occurred while updating review'));
110
            }
111
            return $this->redirect(
112
                Url::toRoute(
113
                    [
114
                        'view',
115
                        'id' => $review->id
116
                    ]
117
                )
118
            );
119
        }
120
    }
121
122
    public function actionMarkSpam($id, $spam = 1)
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...
123
    {
124
        if ($spam === 1) {
125
            $message = Yii::t('app', 'Entry successfully marked as spam');
126
        } else {
127
            $message = Yii::t('app', 'Entry successfully marked as not spam');
128
        }
129
        /** @var Submission $submission */
130
        $submission = Submission::findOne($id);
131
        if (is_null($submission)) {
132
            throw new NotFoundHttpException;
133
        }
134
        $submission->spam = $spam;
135
        if ($spam == 1) {
136
            /** @var Review $review */
137
            $review = Review::findOne(['submission_id' => $id]);
138
            if (!is_null($review)) {
139
                $review->status = Review::STATUS_NOT_APPROVED;
140
                $review->save(true, ['status']);
141
            }
142
        }
143
        if ($submission->save(true, ['spam'])) {
144
            Yii::$app->session->setFlash('success', $message);
145
        }
146
        return $this->redirect(
147
            Url::toRoute(
148
                [
149
                    'view',
150
                    'id' => $id
151
                ]
152
            )
153
        );
154
    }
155
156
    /**
157
     * @param $id
158
     * @param null $returnUrl
159
     * @return Response
160
     * @throws NotFoundHttpException
161
     * @throws \Exception
162
     */
163
    public function actionDelete($id, $returnUrl = null)
164
    {
165
        $model = $this->loadModel($id);
166
        $parent_id = $model->parent_id;
167
        if ($model->delete()) {
168
            Yii::$app->session->setFlash('info', Yii::t('app', 'Object removed'));
169
        }
170
171
        $returnUrl = !empty($returnUrl)
172
            ? $returnUrl
173
            : (0 === intval($parent_id) ? Url::toRoute(['index']) : Url::toRoute(['view', 'id' => $parent_id]));
174
        return $this->redirect($returnUrl);
175
    }
176
177
    /**
178
     * @param array $returnUrl
179
     * @return Response
180
     * @throws \Exception
181
     */
182
    public function actionRemoveAll($returnUrl = ['index'])
183
    {
184
        $items = Yii::$app->request->post('items', []);
185
        if (!empty($items)) {
186
            $items = Review::findAll(['id' => $items]);
187
            foreach ($items as $item) {
188
                $item->delete();
189
            }
190
            Yii::$app->session->setFlash('info', Yii::t('app', 'Objects removed'));
191
        }
192
        return $this->redirect($returnUrl);
193
    }
194
195
    /**
196
     * Load review model by id
197
     * @param $id
198
     * @return Review
199
     * @throws NotFoundHttpException
200
     */
201
    protected function loadModel($id)
202
    {
203
        $model = Review::findOne($id);
204
        if (is_null($model)) {
205
            throw new NotFoundHttpException;
206
        }
207
        return $model;
208
    }
209
210
    public function actionCreate($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...
211
    {
212
        $parent_id = intval($parent_id);
213
        $model = new Review();
214
        $model->loadDefaultValues();
215
216
        if (0 === $parent_id) {
217
            $model->parent_id = $parent_id;
218
            $model->submission_id = 0;
219
            $model->object_model_id = 0;
220
            $model->object_id = 0;
221
        } elseif (null !== $parent = Review::findOne(['id' => $parent_id])) {
222
            /** @var Review $parent */
223
            $model->parent_id = $parent_id;
224
            $model->object_id = $parent->object_id;
225
            $model->object_model_id = $parent->object_model_id;
226
            $model->root_id = $parent->root_id;
227
            $model->submission_id = $parent->submission_id;
228
        }
229
230 View Code Duplication
        if (true === Yii::$app->request->isPost) {
231
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
232
                return $this->redirect(Url::toRoute(['view', 'id' => $model->id]));
233
            } else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
234
                // @todo add alert and may be something else here
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
235
            }
236
        }
237
238
        return $this->render('edit', [
239
            'review' => $model
240
        ]);
241
    }
242
243
    /**
244
     * @return array
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use array<string,false|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...
245
     */
246
    public function actionAjaxSearch()
247
    {
248
        Yii::$app->response->format = Response::FORMAT_JSON;
249
        $search = \Yii::$app->request->get('search', []);
250
        $object = !empty($search['object']) ?  intval($search['object']) : 0;
251
        $term = !empty($search['term']) ?  $search['term'] : '';
252
253
        $result = [
254
            'more' => false,
255
            'results' => []
256
        ];
257
258
        if (null === $object = Object::findById($object)) {
259
            return $result;
260
        }
261
262
        /** @var ActiveRecord $class */
263
        $class = $object->object_class;
264
        $list = [
265
            Product::className(),
266
            Category::className(),
267
            Page::className(),
268
        ];
269
        if (!in_array($class, $list)) {
270
            return $result;
271
        }
272
273
        $query = $class::find()
274
            ->select('id, name, "#" `url`')
275
            ->andWhere(['like', 'name', $term])
276
            ->asArray(true);
277
        $result['results'] = array_values($query->all());
278
        array_walk($result['results'],
279
            function (&$val) use ($class)
280
            {
281
                if (null !== $model = $class::findOne(['id' => $val['id']])) {
282
                    if (Product::className() === $model->className()) {
283
                        $val['url'] = Url::toRoute([
284
                            '@product',
285
                            'model' => $model,
286
                            'category_group_id' => $model->category->category_group_id,
287
                        ]);
288
                    } elseif (Category::className() === $model->className()) {
289
                        $val['url'] = Url::toRoute([
290
                            '@category',
291
                            'last_category_id' => $model->id,
292
                            'category_group_id' => $model->category_group_id,
293
                        ]);
294
                    } else if (Page::className() === $model->className()) {
295
                        $val['url'] = Url::toRoute([
296
                            '@article',
297
                            'id' => $model->id,
298
                        ]);
299
                    }
300
                }
301
            });
302
303
        return $result;
304
    }
305
306
    /**
307
     * @return array
308
     */
309
    public function actionAjaxGetTree($root_id = null, $current_id = 0)
310
    {
311
        Yii::$app->response->format = Response::FORMAT_JSON;
312
313
        $q = Review::find()
314
            ->select('*')
315
            ->where(['root_id' => $root_id])
316
            ->orderBy(['parent_id' => SORT_ASC])
317
            ->asArray(true);
318
319
        $result = array_reduce($q->all(),
320
            function ($res, $item) use ($current_id)
321
            {
322
                $res[] = [
323
                    'id' => $item['id'],
324
                    'parent' => 0 === intval($item['parent_id']) ? '#' : $item['parent_id'],
325
                    'text' => $item['id'],
326
                    'type' => intval($item['id']) === intval($current_id) ? 'current' : 'leaf',
327
                    'a_attr' => [
328
                        'data-id' => $item['id'],
329
                    ]
330
                ];
331
                return $res;
332
            }, []);
333
334
        return $result;
335
    }
336
}
337