MenuController   B
last analyzed

Complexity

Total Complexity 46

Size/Duplication

Total Lines 280
Duplicated Lines 18.57 %

Coupling/Cohesion

Components 2
Dependencies 14

Importance

Changes 8
Bugs 1 Features 0
Metric Value
wmc 46
c 8
b 1
f 0
lcom 2
cbo 14
dl 52
loc 280
rs 8.3999

12 Methods

Rating   Name   Duplication   Size   Complexity  
B behaviors() 24 24 1
B actionIndex() 0 22 5
A actionCreate() 0 10 3
A actionUpdate() 0 14 4
A actionDelete() 0 7 1
C actionCreateMenuItem() 28 44 14
B actionDeleteMenuItem() 0 15 5
A findModel() 0 8 2
A findMenuItem() 0 8 2
A findPost() 0 8 2
A findTerm() 0 8 2
B saveMenuItem() 0 18 5

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 MenuController 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 MenuController, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * @link http://www.writesdown.com/
4
 * @copyright Copyright (c) 2015 WritesDown
5
 * @license http://www.writesdown.com/license/
6
 */
7
8
namespace backend\controllers;
9
10
use common\components\Json;
11
use common\models\Menu;
12
use common\models\MenuItem;
13
use common\models\Post;
14
use common\models\PostType;
15
use common\models\Taxonomy;
16
use common\models\Term;
17
use Yii;
18
use yii\filters\AccessControl;
19
use yii\filters\VerbFilter;
20
use yii\helpers\ArrayHelper;
21
use yii\web\Controller;
22
use yii\web\NotFoundHttpException;
23
24
/**
25
 * MenuController, controlling the actions for Menu and MenuItem model.
26
 *
27
 * @author Agiel K. Saputra <[email protected]>
28
 * @since 0.1.0
29
 */
30
class MenuController extends Controller
31
{
32
    /**
33
     * @inheritdoc
34
     */
35 View Code Duplication
    public function behaviors()
0 ignored issues
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...
36
    {
37
        return [
38
            'access' => [
39
                'class' => AccessControl::className(),
40
                'rules' => [
41
                    [
42
                        'actions' => ['index', 'update', 'create', 'delete', 'create-menu-item', 'delete-menu-item'],
43
                        'allow' => true,
44
                        'roles' => ['administrator'],
45
                    ],
46
                ],
47
            ],
48
            'verbs' => [
49
                'class' => VerbFilter::className(),
50
                'actions' => [
51
                    'delete' => ['post'],
52
                    'update' => ['post'],
53
                    'create-menu-item' => ['post'],
54
                    'delete-menu-item' => ['post'],
55
                ],
56
            ],
57
        ];
58
    }
59
60
    /**
61
     * Displays menu page consists of CRUD for Menu and MenuItem model.
62
     *
63
     * @param null $id
64
     * @return mixed
65
     */
66
    public function actionIndex($id = null)
67
    {
68
        $model = new Menu();
69
        $postTypes = PostType::find()->where(['menu_builder' => PostType::MENU_BUILDER])->all();
70
        $taxonomies = Taxonomy::find()->where(['menu_builder' => Taxonomy::MENU_BUILDER])->all();
71
72
        if ($available = ArrayHelper::map(Menu::find()->all(), 'id', 'title')) {
73
            if ($id === null && $available) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $available of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
74
                reset($available);
75
                $id = key($available);
76
            }
77
            $selected = $this->findModel($id);
78
        }
79
80
        return $this->render('index', [
81
            'model' => $model,
82
            'available' => $available,
83
            'selected' => isset($selected) ? $selected : null,
84
            'postTypes' => $postTypes,
85
            'taxonomies' => $taxonomies,
86
        ]);
87
    }
88
89
    /**
90
     * Creates a new Menu model.
91
     * If creation is successful, the browser will be redirected to the 'index' page.
92
     *
93
     * @return mixed
94
     */
95
    public function actionCreate()
96
    {
97
        $model = new Menu();
98
99
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
100
            return $this->redirect(['index', 'id' => $model->id]);
101
        }
102
103
        return $this->redirect(['index']);
104
    }
105
106
    /**
107
     * Updates an existing Menu model.
108
     * If update is successful, the browser will be redirected to the 'view' page.
109
     *
110
     * @param integer $id
111
     * @return mixed
112
     */
113
    public function actionUpdate($id)
114
    {
115
        $model = $this->findModel($id);
116
117
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
0 ignored issues
show
Bug introduced by
The method load 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...
Bug introduced by
The method save 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...
118
            if ($menuOrder = Yii::$app->request->post('MenuOrder')) {
119
                $this->saveMenuItem(Json::decode($menuOrder));
120
            }
121
        }
122
123
        Yii::$app->getSession()->setFlash('success', Yii::t('writesdown', 'Menu successfully saved.'));
0 ignored issues
show
Bug introduced by
The method getSession does only exist in yii\web\Application, but not in yii\console\Application.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
124
125
        return $this->redirect(['/menu/index', 'id' => $id]);
126
    }
127
128
    /**
129
     * Deletes an existing Menu model.
130
     * If deletion is successful, the browser will be redirected to the 'index' page.
131
     *
132
     * @return mixed
133
     * @throws NotFoundHttpException
134
     * @throws \Exception
135
     */
136
    public function actionDelete()
137
    {
138
        $id = Yii::$app->request->post('id');
139
        $this->findModel($id)->delete();
0 ignored issues
show
Bug introduced by
The method delete cannot be called on $this->findModel($id) (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...
140
141
        return $this->redirect(['index']);
142
    }
143
144
    /**
145
     * Create MenuItem models.
146
     *
147
     * @param int $id
148
     * @return string
149
     */
150
    public function actionCreateMenuItem($id)
151
    {
152
        $items = '';
153
154
        if (Yii::$app->request->post('type') === 'link') {
155
            $model = new MenuItem();
156
            $model->menu_id = $id;
157
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
158
                $items .= $this->renderPartial('_render-item', ['item' => $model, 'wrap' => 'true']);
159
            }
160
        }
161
162 View Code Duplication
        if (Yii::$app->request->post('type') === 'post' && $postIds = Yii::$app->request->post('postIds')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
163
            foreach ($postIds as $postId) {
164
                if ($post = $this->findPost($postId)) {
165
                    $model = new MenuItem([
166
                        'menu_id' => $id,
167
                        'label' => $post->title,
168
                        'url' => $post->getUrl(),
0 ignored issues
show
Bug introduced by
The method getUrl cannot be called on $post (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...
169
                    ]);
170
                    if ($model->save()) {
171
                        $items .= $this->renderPartial('_render-item', ['item' => $model, 'wrap' => 'true']);
172
                    }
173
                }
174
            }
175
        }
176
177 View Code Duplication
        if (Yii::$app->request->post('type') === 'taxonomy' && $termIds = Yii::$app->request->post('termIds')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
178
            foreach ($termIds as $termId) {
179
                if ($term = $this->findTerm($termId)) {
180
                    $model = new MenuItem([
181
                        'menu_id' => $id,
182
                        'label' => $term->name,
183
                        'url' => $term->getUrl(),
0 ignored issues
show
Bug introduced by
The method getUrl cannot be called on $term (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...
184
                    ]);
185
                    if ($model->save()) {
186
                        $items .= $this->renderPartial('_render-item', ['item' => $model, 'wrap' => 'true']);
187
                    }
188
                }
189
            }
190
        }
191
192
        return $items;
193
    }
194
195
    /**
196
     * Delete an existing MenuItem model via AJAX request.
197
     *
198
     * @throws NotFoundHttpException
199
     * @throws \Exception
200
     */
201
    public function actionDeleteMenuItem()
202
    {
203
        /* @var $children \common\models\MenuItem[] */
204
        if ($id = Yii::$app->request->post('id')) {
205
            $model = $this->findMenuItem($id);
206
            if ($model && $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...
207
                $children = MenuItem::find()->where(['parent' => $model->id])->all();
208
                foreach ($children as $child) {
209
                    $child->updateAttributes(['parent' => $model->parent]);
210
                }
211
            } else {
212
                throw new NotFoundHttpException(Yii::t('writesdown', 'The requested page does not exist.'));
213
            }
214
        }
215
    }
216
217
    /**
218
     * Save menu item recursively based on parent and child.
219
     *
220
     * @param array $menuOrder
221
     * @param int $menuParent
222
     */
223
    protected function saveMenuItem($menuOrder, $menuParent = 0)
224
    {
225
        foreach ($menuOrder as $key => $order) {
226
            $menuItem = Yii::$app->request->post('MenuItem')[$order['id']];
227
            if ($model = $this->findMenuItem($order['id'])) {
228
                $model->setAttributes($menuItem);
0 ignored issues
show
Bug introduced by
The method setAttributes 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...
229
                $model->setAttributes([
0 ignored issues
show
Bug introduced by
The method setAttributes 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...
230
                    'parent' => $menuParent,
231
                    'order' => $key,
232
                ]);
233
                if ($model->save()) {
0 ignored issues
show
Bug introduced by
The method save 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...
234
                    if ($orderItems = ArrayHelper::getValue($order, 'items')) {
235
                        $this->saveMenuItem($orderItems, $model->id);
236
                    }
237
                }
238
            }
239
        }
240
    }
241
242
    /**
243
     * Finds the Menu model based on its primary key value.
244
     * If the model is not found, a 404 HTTP exception will be thrown.
245
     *
246
     * @param integer $id
247
     * @return Menu the loaded model
248
     * @throws NotFoundHttpException if the model cannot be found
249
     */
250
    protected function findModel($id)
251
    {
252
        if (($model = Menu::findOne($id)) !== null) {
253
            return $model;
254
        }
255
256
        throw new NotFoundHttpException(Yii::t('writesdown', 'The requested page does not exist.'));
257
    }
258
259
    /**
260
     * Finds the MenuItem model based on its primary key value.
261
     * If the model is not found, it will return false.
262
     *
263
     * @param integer $id
264
     * @return MenuItem the loaded model
265
     * @throws NotFoundHttpException if the model cannot be found
266
     */
267
    protected function findMenuItem($id)
268
    {
269
        if (($model = MenuItem::findOne($id)) !== null) {
270
            return $model;
271
        }
272
273
        throw new NotFoundHttpException(Yii::t('writesdown', 'The requested page does not exist.'));
274
    }
275
276
    /**
277
     * Finds the Post model based on its primary key value.
278
     * If the model is not found, it will return false.
279
     *
280
     * @param integer $id
281
     * @return Post the loaded model
282
     * @throws NotFoundHttpException if the model cannot be found
283
     */
284
    protected function findPost($id)
285
    {
286
        if (($model = Post::findOne($id)) !== null) {
287
            return $model;
288
        }
289
290
        throw new NotFoundHttpException(Yii::t('writesdown', 'The requested page does not exist.'));
291
    }
292
293
    /**
294
     * Finds the Term model based on its primary key value.
295
     * If the model is not found, it will return false.
296
     *
297
     * @param integer $id
298
     * @return Term the loaded model
299
     * @throws NotFoundHttpException if the model cannot be found
300
     */
301
    protected function findTerm($id)
302
    {
303
        if (($model = Term::findOne($id)) !== null) {
304
            return $model;
305
        }
306
307
        throw new NotFoundHttpException(Yii::t('writesdown', 'The requested page does not exist.'));
308
    }
309
}
310