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

BackendReviewController   C

Complexity

Total Complexity 45

Size/Duplication

Total Lines 314
Duplicated Lines 8.28 %

Coupling/Cohesion

Components 1
Dependencies 16

Importance

Changes 1
Bugs 1 Features 0
Metric Value
wmc 45
lcom 1
cbo 16
dl 26
loc 314
rs 6.8437
c 1
b 1
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
B actionAjaxSearch() 0 56 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)
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()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $review->update() of type false|integer is loosely compared to true; 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...
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
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...
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 Best Practice introduced by
The expression $model->delete() of type false|integer is loosely compared to true; 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...
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]));
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 = Object::find()->select("object_class")->column();
265
        if (!in_array($class, $list)) {
266
            return $result;
267
        }
268
269
        $query = $class::find()
270
            ->select('id, name, "#" `url`')
271
            ->andWhere(['like', 'name', $term])
272
            ->asArray(true);
273
        $result['results'] = array_values($query->all());
274
        array_walk($result['results'],
275
            function (&$val) use ($class)
276
            {
277
                if (null !== $model = $class::findOne(['id' => $val['id']])) {
278
                    $product = Yii::$container->get(Product::class);
279
                    if (get_class($product) === $model->className()) {
280
                        $val['url'] = Url::toRoute([
281
                            '@product',
282
                            'model' => $model,
283
                            'category_group_id' => $model->category->category_group_id,
284
                        ]);
285
                    } elseif (Category::className() === $model->className()) {
286
                        $val['url'] = Url::toRoute([
287
                            '@category',
288
                            'last_category_id' => $model->id,
289
                            'category_group_id' => $model->category_group_id,
290
                        ]);
291
                    } else if (Page::className() === $model->className()) {
292
                        $val['url'] = Url::toRoute([
293
                            '@article',
294
                            'id' => $model->id,
295
                        ]);
296
                    }
297
                }
298
            });
299
300
        return $result;
301
    }
302
303
    /**
304
     * @return array
305
     */
306
    public function actionAjaxGetTree($root_id = null, $current_id = 0)
307
    {
308
        Yii::$app->response->format = Response::FORMAT_JSON;
309
310
        $q = Review::find()
311
            ->select('*')
312
            ->where(['root_id' => $root_id])
313
            ->orderBy(['parent_id' => SORT_ASC])
314
            ->asArray(true);
315
316
        $result = array_reduce($q->all(),
317
            function ($res, $item) use ($current_id)
318
            {
319
                $res[] = [
320
                    'id' => $item['id'],
321
                    'parent' => 0 === intval($item['parent_id']) ? '#' : $item['parent_id'],
322
                    'text' => $item['id'],
323
                    'type' => intval($item['id']) === intval($current_id) ? 'current' : 'leaf',
324
                    'a_attr' => [
325
                        'data-id' => $item['id'],
326
                    ]
327
                ];
328
                return $res;
329
            }, []);
330
331
        return $result;
332
    }
333
}
334