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.
Test Setup Failed
Push — filters ( 233a3a...88ffb1 )
by Alexander
29:32
created

BackendReviewController   C

Complexity

Total Complexity 45

Size/Duplication

Total Lines 317
Duplicated Lines 8.2 %

Coupling/Cohesion

Components 1
Dependencies 16

Importance

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

11 Methods

Rating   Name   Duplication   Size   Complexity  
A behaviors() 14 14 1
A actionIndex() 0 22 1
B actionView() 5 20 5
B actionUpdateStatus() 0 33 5
B actionMarkSpam() 0 33 6
A actionDelete() 0 13 4
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()
1 ignored issue
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...
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();
0 ignored issues
show
Bug introduced by
The method update cannot be called on $review (of type array|boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
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()) {
0 ignored issues
show
Bug introduced by
The method update cannot be called on $review (of type array|boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
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)
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()) {
0 ignored issues
show
Bug introduced by
The method delete cannot be called on $model (of type array|boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
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
0 ignored issues
show
Documentation introduced by
Should the return type not be array|boolean? Also, consider making the array more specific, something like array<String>, or String[].

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

If the return type contains the type array, this check recommends the use of a more specific type like String[] or array<String>.

Loading history...
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]));
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<app\modules\review\models\Review>. 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...
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()) {
0 ignored issues
show
Bug introduced by
The method className cannot be called on $model (of type array|boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
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()) {
0 ignored issues
show
Bug introduced by
The method className cannot be called on $model (of type array|boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
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()) {
0 ignored issues
show
Bug introduced by
The method className cannot be called on $model (of type array|boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
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