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

PageController   B

Complexity

Total Complexity 38

Size/Duplication

Total Lines 336
Duplicated Lines 27.38 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 38
c 1
b 0
f 0
lcom 1
cbo 8
dl 92
loc 336
rs 8.3999

8 Methods

Rating   Name   Duplication   Size   Complexity  
A actionIndex() 22 22 2
A actionDelete() 0 19 4
A behaviors() 14 14 1
B actions() 0 42 1
A actionRemoveAll() 0 12 3
A actionRestore() 0 21 3
C actionClone() 47 96 11
C actionEdit() 9 81 13

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\page\backend;
4
5
use app\backend\actions\PropertyHandler;
6
use app\backend\events\BackendEntityEditEvent;
7
use app\models\Object;
8
use app\models\ObjectPropertyGroup;
9
use app\models\Property;
10
use app\modules\image\models\Image;
11
use app\modules\image\widgets\views\AddImageAction;
12
use app\modules\page\models\Page;
13
use app\models\ViewObject;
14
use app\properties\HasProperties;
15
use app\modules\image\widgets\RemoveAction;
16
use app\modules\image\widgets\SaveInfoAction;
17
use app\modules\image\widgets\UploadAction;
18
use devgroup\JsTreeWidget\AdjacencyFullTreeDataAction;
19
use devgroup\JsTreeWidget\TreeNodeMoveAction;
20
use devgroup\JsTreeWidget\TreeNodesReorderAction;
21
use Yii;
22
use yii\db\Query;
23
use yii\filters\AccessControl;
24
use yii\helpers\ArrayHelper;
25
use yii\helpers\Url;
26
use yii\web\NotFoundHttpException;
27
use app\backend\actions\MassPublishAction;
28
29
class PageController extends \app\backend\components\BackendController
30
{
31
32
    const BACKEND_PAGE_EDIT = 'backend-page-edit';
33
    const BACKEND_PAGE_EDIT_SAVE = 'backend-page-edit-save';
34
    const BACKEND_PAGE_EDIT_FORM = 'backend-page-edit-form';
35
    const BACKEND_PAGE_AFTER_SAVE = 'backend-page-after-save';
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' => ['content manage'],
46
                    ],
47
                ],
48
            ],
49
        ];
50
    }
51
52
    public function actions()
53
    {
54
        return [
55
            'getTree' => [
56
                'class' => AdjacencyFullTreeDataAction::className(),
57
                'class_name' => Page::className(),
58
                'model_label_attribute' => 'name',
59
            ],
60
            'addImage' => [
61
                'class' => AddImageAction::className(),
62
            ],
63
            'upload' => [
64
                'class' => UploadAction::className(),
65
                'upload' => 'theme/resources/product-images',
66
            ],
67
            'remove' => [
68
                'class' => RemoveAction::className(),
69
                'uploadDir' => 'theme/resources/product-images',
70
            ],
71
            'save-info' => [
72
                'class' => SaveInfoAction::className(),
73
            ],
74
            'property-handler' => [
75
                'class' => PropertyHandler::className(),
76
                'modelName' => Page::className()
77
            ],
78
            'move' => [
79
                'class' => TreeNodeMoveAction::className(),
80
                'className' => Page::className(),
81
                'saveAttributes' => ['slug_compiled'],
82
            ],
83
            'reorder' => [
84
                'class' => TreeNodesReorderAction::className(),
85
                'className' => Page::className(),
86
            ],
87
            'publish-switch' => [
88
                'class' => MassPublishAction::className(),
89
                'modelName' => Page::className(),
90
                'attribute' => 'published',
91
            ]
92
        ];
93
    }
94
95 View Code Duplication
    public function actionIndex($parent_id = 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...
96
    {
97
        $searchModel = new Page();
98
        $searchModel->parent_id = $parent_id;
99
100
        $params = Yii::$app->request->get();
101
        $dataProvider = $searchModel->search($params);
102
103
        $model = null;
104
        if ($parent_id > 0) {
105
            $model = Page::findOne($parent_id);
106
        }
107
108
        return $this->render(
109
            'index',
110
            [
111
                'dataProvider' => $dataProvider,
112
                'searchModel' => $searchModel,
113
                'model' => $model,
114
            ]
115
        );
116
    }
117
118
    public function actionEdit($parent_id, $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...
119
    {
120
        $object = Object::getForClass(Page::className());
121
122
        /** @var null|Page|HasProperties $model */
123
        $model = new Page;
124
        $model->published = 1;
125
        if ($id !== null) {
126
            $model = Page::findOne($id);
127
            if ($model === null) {
128
                throw new NotFoundHttpException;
129
            }
130
        }
131
        $model->parent_id = $parent_id;
132
133
        $event = new BackendEntityEditEvent($model);
134
        $this->trigger(self::BACKEND_PAGE_EDIT, $event);
135
136
        $post = \Yii::$app->request->post();
137
        if ($event->isValid && $model->load($post)) {
138
            $saveStateEvent = new BackendEntityEditEvent($model);
139
            $this->trigger(self::BACKEND_PAGE_EDIT_SAVE, $saveStateEvent);
140
141
            if ($saveStateEvent->isValid && $model->validate()) {
142
                $save_result = $model->save();
143
                $model->saveProperties($post);
144
145 View Code Duplication
                if (null !== $view_object = ViewObject::getByModel($model, true)) {
146
                    if ($view_object->load($post, 'ViewObject')) {
147
                        if ($view_object->view_id <= 0) {
148
                            $view_object->delete();
149
                        } else {
150
                            $view_object->save();
151
                        }
152
                    }
153
                }
154
155
                if ($save_result) {
156
                    $modelAfterSaveEvent = new BackendEntityEditEvent($model);
157
                    $this->trigger(self::BACKEND_PAGE_AFTER_SAVE, $modelAfterSaveEvent);
158
159
                    $this->runAction('save-info', ['model_id' => $model->id]);
160
                    Yii::$app->session->setFlash('info', Yii::t('app', 'Object saved'));
161
                    $returnUrl = Yii::$app->request->get('returnUrl', ['/page/backend/index']);
162
                    switch (Yii::$app->request->post('action', 'save')) {
163
                        case 'next':
164
                            return $this->redirect(
165
                                [
166
                                    '/page/backend/edit',
167
                                    'returnUrl' => $returnUrl,
168
                                    'parent_id' => Yii::$app->request->get('parent_id', null)
169
                                ]
170
                            );
171
                        case 'back':
172
                            return $this->redirect($returnUrl);
173
                        default:
174
                            return $this->redirect(
175
                                Url::toRoute(
176
                                    [
177
                                        '/page/backend/edit',
178
                                        'id' => $model->id,
179
                                        'returnUrl' => $returnUrl,
180
                                        'parent_id' => $model->parent_id
181
                                    ]
182
                                )
183
                            );
184
                    }
185
                } else {
186
                    \Yii::$app->session->setFlash('error', Yii::t('app', 'Cannot update data'));
187
                }
188
            }
189
        }
190
191
        return $this->render(
192
            'page-form',
193
            [
194
                'model' => $model,
195
                'object' => $object,
196
            ]
197
        );
198
    }
199
200
    /*
201
     *
202
     */
203
    public function actionDelete($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...
204
    {
205
        if ((null === $id) || (null === $model = Page::findOne($id))) {
206
            throw new NotFoundHttpException;
207
        }
208
209
        if (!$model->delete()) {
210
            Yii::$app->session->setFlash('info', Yii::t('app', 'The object is placed in the cart'));
211
        } else {
212
            Yii::$app->session->setFlash('info', Yii::t('app', 'Object removed'));
213
        }
214
215
        return $this->redirect(
216
            Yii::$app->request->get(
217
                'returnUrl',
218
                Url::toRoute(['index', 'parent_id' => $model->parent_id])
219
            )
220
        );
221
    }
222
223
    public function actionRemoveAll($parent_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...
224
    {
225
        $items = Yii::$app->request->post('items', []);
226
        if (!empty($items)) {
227
            $items = Page::find()->where(['in', 'id', $items])->all();
228
            foreach ($items as $item) {
229
                $item->delete();
230
            }
231
        }
232
233
        return $this->redirect(['index', 'parent_id' => $parent_id]);
234
    }
235
236
    /*
237
     *
238
     */
239
    public function actionRestore($id = null, $parent_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...
240
    {
241
        if (null === $id) {
242
            new NotFoundHttpException();
243
        }
244
245
        if (null === $model = Page::findOne(['id' => $id])) {
246
            new NotFoundHttpException();
247
        }
248
249
        $model->restoreFromTrash();
250
251
        Yii::$app->session->setFlash('success', Yii::t('app', 'Object successfully restored'));
252
253
        return $this->redirect(
254
            Yii::$app->request->get(
255
                'returnUrl',
256
                Url::toRoute(['edit', 'id' => $id, 'parent_id' => $parent_id])
257
            )
258
        );
259
    }
260
261
262
    /**
263
     * Clone page action.
264
     * @param integer $id
265
     * @param array|string $returnUrl
266
     * @throws \yii\web\NotFoundHttpException
267
     */
268
    public function actionClone($id, $returnUrl = ['index'])
269
    {
270
        /** @var Page|HasProperties $model */
271
        $model = Page::findOne($id);
272
        if ($model === null) {
273
            throw new NotFoundHttpException;
274
        }
275
276
        /** @var Page|HasProperties $newModel */
277
        $newModel = new Page;
278
        $newModel->setAttributes($model->attributes, false);
279
        $time = time();
280
        $newModel->name .= ' (copy ' . date('Y-m-d h:i:s', $time) . ')';
281
        $newModel->slug .= '-copy-' . date('Ymdhis', $time);
282
        $newModel->title .= '-copy-' . date('Ymdhis', $time);
283
        $newModel->id = null;
284 View Code Duplication
        if ($newModel->validate() === false) {
285
            $newModel->slug = substr(uniqid() . "-" . $model->slug, 0, 80);
286
        }
287
        if ($newModel->save()) {
288
            $object = Object::getForClass(get_class($newModel));
289
            $query = new Query();
290
291
            // save images bindings
292
            $params = $query->select(
293
                ['object_id', 'filename', 'image_title', 'image_alt', 'sort_order']
294
            )->from(Image::tableName())->where(
295
                [
296
                    'object_id' => $object->id,
297
                    'object_model_id' => $model->id
298
                ]
299
            )->all();
300 View Code Duplication
            if (!empty($params)) {
301
                $rows = [];
302
                foreach ($params as $param) {
303
                    $rows[] = [
304
                        $param['object_id'],
305
                        $newModel->id,
306
                        $param['filename'],
307
                        $param['image_title'],
308
                        $param['image_alt'],
309
                        $param['sort_order'],
310
                    ];
311
                }
312
                Yii::$app->db->createCommand()->batchInsert(
313
                    Image::tableName(),
314
                    [
315
                        'object_id',
316
                        'object_model_id',
317
                        'filename',
318
                        'image_title',
319
                        'image_alt',
320
                        'sort_order',
321
                    ],
322
                    $rows
323
                )->execute();
324
            }
325
            $newModelProps = [];
326 View Code Duplication
            foreach (array_keys($model->propertyGroups) as $key) {
327
                $opg = new ObjectPropertyGroup();
328
                $opg->attributes = [
329
                    'object_id' => $object->id,
330
                    'object_model_id' => $newModel->id,
331
                    'property_group_id' => $key,
332
                ];
333
                $opg->save();
334
                $props = Property::getForGroupId($key);
335
                foreach ($props as $prop) {
0 ignored issues
show
Bug introduced by
The expression $props of type null|array<integer,object<app\models\Property>> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
336
                    $propValues = $model->getPropertyValuesByPropertyId($prop->id);
337
                    if ($propValues !== null) {
338
                        foreach ($propValues->values as $val) {
339
                            $valueToSave = ArrayHelper::getValue($val, 'psv_id', $val['value']);
340
                            $newModelProps[$prop->key][] = $valueToSave;
341
                        }
342
                    }
343
                }
344
            }
345
            $newModel->saveProperties(
346
                [
347
                    'Properties_Page_' . $newModel->id => $newModelProps,
348
                ]
349
            );
350
            $view = ViewObject::findOne(['object_id' => $model->object->id, 'object_model_id' => $model->id]);
351
            if ($view !== null) {
352
                $newView = new ViewObject;
353
                $newView->setAttributes($view->attributes, false);
354
                $newView->id = null;
355
                $newView->object_model_id = $newModel->id;
356
                $newView->save();
357
            }
358
            Yii::$app->session->setFlash('success', Yii::t('app', 'Page has been cloned successfully.'));
359
            $this->redirect(
360
                ['edit', 'id' => $newModel->id, 'parent_id' => $newModel->parent_id, 'returnUrl' => $returnUrl]
361
            );
362
        }
363
    }
364
}
365