ContentController   A
last analyzed

Complexity

Total Complexity 32

Size/Duplication

Total Lines 301
Duplicated Lines 18.6 %

Coupling/Cohesion

Components 1
Dependencies 10

Importance

Changes 0
Metric Value
wmc 32
lcom 1
cbo 10
dl 56
loc 301
rs 9.84
c 0
b 0
f 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
A behaviors() 18 18 1
A actionIndex() 0 25 2
A actionView() 0 8 1
C actionGenerate() 0 54 12
A actionUpload() 15 15 3
A actionSideload() 15 15 3
A actionUpdate() 0 13 3
A actionDelete() 0 8 1
A actionPreview() 0 9 1
A actionToggle() 0 10 1
A findViewableModel() 0 9 2
A findModel() 8 8 2

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\controllers;
4
5
use Yii;
6
use app\models\Content;
7
use app\models\ContentType;
8
use app\models\Flow;
9
use yii\helpers\Url;
10
use yii\data\ActiveDataProvider;
11
use yii\web\UploadedFile;
12
use yii\web\NotFoundHttpException;
13
use yii\filters\AccessControl;
14
use yii\filters\VerbFilter;
15
16
/**
17
 * ContentController implements the CRUD actions for Content model.
18
 */
19
class ContentController extends BaseController
20
{
21
    /**
22
     * {@inheritdoc}
23
     */
24 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...
25
    {
26
        return [
27
            'verbs' => [
28
                'class' => VerbFilter::class,
29
                'actions' => [
30
                    'delete' => ['POST'],
31
                ],
32
            ],
33
            'access' => [
34
                'class' => AccessControl::class,
35
                'only' => ['index', 'view', 'generate', 'upload', 'sideload', 'update', 'delete', 'toggle'],
36
                'rules' => [
37
                    ['allow' => true, 'actions' => ['index', 'view', 'generate', 'upload', 'sideload', 'update', 'delete', 'toggle'], 'roles' => ['@']],
38
                ],
39
            ],
40
        ];
41
    }
42
43
    /**
44
     * Lists all Content models.
45
     *
46
     * @return string
47
     */
48
    public function actionIndex()
49
    {
50
        $query = Content::availableQuery(Yii::$app->user);
51
        if ($query === null) {
52
            throw new \yii\web\ForbiddenHttpException(Yii::t('app', 'You do not have enough rights to view this content.'));
53
        }
54
55
        $dataProvider = new ActiveDataProvider([
56
            'query' => $query,
57
        ]);
58
59
        $dataProvider->sort->attributes['type.name'] = [
60
            'asc' => [ContentType::tableName() . '.id' => SORT_ASC],
61
            'desc' => [ContentType::tableName() . '.id' => SORT_DESC],
62
        ];
63
64
        $dataProvider->sort->attributes['flow.name'] = [
65
            'asc' => [Flow::tableName() . '.id' => SORT_ASC],
66
            'desc' => [Flow::tableName() . '.id' => SORT_DESC],
67
        ];
68
69
        return $this->render('index', [
70
            'dataProvider' => $dataProvider,
71
        ]);
72
    }
73
74
    /**
75
     * Displays a single Content model.
76
     *
77
     * @param int $id
78
     *
79
     * @return string
80
     */
81
    public function actionView($id)
82
    {
83
        $model = $this->findViewableModel($id, Yii::$app->user);
84
85
        return $this->render('view', [
86
            'model' => $model,
87
        ]);
88
    }
89
90
    /**
91
     * Creates a new Content model with type choice assistance.
92
     *
93
     * @param int    $flowId
94
     * @param string $type   content type
95
     *
96
     * @return \yii\web\Response|string redirect or render
97
     */
98
    public function actionGenerate($flowId, $type = null)
99
    {
100
        $flow = Flow::findOne($flowId);
101
        if ($flow === null) {
102
            throw new NotFoundHttpException(Yii::t('app', 'The requested flow does not exist.'));
103
        }
104
105
        if (!$flow->canView(Yii::$app->user)) {
106
            throw new \yii\web\ForbiddenHttpException(Yii::t('app', 'You do not have enough rights to view this content.'));
107
        }
108
109
        $contentType = ContentType::findOne($type);
110
        if ($contentType === null) {
111
            $types = ContentType::getAll(false);
112
113
            return $this->render('type-choice', [
114
                'types' => $types,
115
                'flow' => $flowId,
116
            ]);
117
        } else {
118
            $model = new Content(['flow_id' => $flow->id, 'type_id' => $contentType->id]);
119
            if ($model->load(Yii::$app->request->post())) {
120
                if ($model->save()) {
121
                    return $this->redirect(['flow/view', 'id' => $flow->id]);
122
                }
123
            } else {
124
                $model->loadDefaultValues();
125
            }
126
127
            switch ($contentType->input) {
128
                case ContentType::KINDS['FILE']:
129
                    // FILE implies content upload (images/videos)
130
                case ContentType::KINDS['URL']:
131
                    // URL allows content hotlinks, like images
132
                    // There's not much to process, simply input url in data
133
                case ContentType::KINDS['POS']:
134
                    // Latitude & longitude
135
                case ContentType::KINDS['TEXT']:
136
                    // Same as URL, text doesn't require processing
137
                    return $this->render('type/' . $contentType->input, [
138
                        'type' => $contentType,
139
                        'model' => $model,
140
                        'uploadUrl' => Url::to(['content/upload', 'type' => $type]),
141
                        'sideloadUrl' => Url::to(['content/sideload', 'type' => $type]),
142
                    ]);
143
                case ContentType::KINDS['NONE']:
144
                case ContentType::KINDS['RAW']:
145
                    // RAW ContentType doesn't support Content
146
                    // Everything should be handled by ContentType alone
147
                default:
148
                    throw new NotFoundHttpException(Yii::t('app', 'The requested content type is not supported.'));
149
            }
150
        }
151
    }
152
153
    /**
154
     * Receives an uploaded file and responds with filepath.
155
     *
156
     * @api
157
     *
158
     * @param string $type content type
159
     *
160
     * @return string json status
161
     */
162 View Code Duplication
    public function actionUpload($type)
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...
163
    {
164
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
165
166
        if (!Yii::$app->user->can('upload')) {
167
            return ['success' => false, 'message' => Yii::t('app', 'Not authorized')];
168
        }
169
170
        $model = new Content(['type_id' => $type]);
171
        if (($res = $model->type->upload(UploadedFile::getInstanceByName('content'))) !== false) {
172
            return ['success' => true, 'filepath' => $res['tmppath'], 'duration' => $res['duration'], 'filename' => $res['filename']];
173
        }
174
175
        return ['success' => false, 'message' => $model->type->getLoadError()];
176
    }
177
178
    /**
179
     * Receives an url to download on server -- sideloading.
180
     *
181
     * @api
182
     *
183
     * @param string $type content type
184
     * @param string $url
185
     *
186
     * @return string json status
187
     */
188 View Code Duplication
    public function actionSideload($type, $url)
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...
189
    {
190
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
191
192
        if (!Yii::$app->user->can('upload')) {
193
            return ['success' => false, 'message' => Yii::t('app', 'Not authorized')];
194
        }
195
196
        $model = new Content(['type_id' => $type]);
197
        if (($res = $model->type->sideload($url)) !== false) {
198
            return ['success' => true, 'filepath' => $res['tmppath'], 'duration' => $res['duration'], 'filename' => $res['filename']];
199
        }
200
201
        return ['success' => false, 'message' => $model->type->getLoadError()];
202
    }
203
204
    /**
205
     * Updates an existing Content model.
206
     * If update is successful, the browser will be redirected to the 'view' page.
207
     *
208
     * @param int $id
209
     *
210
     * @return \yii\web\Response|string redirect or render
211
     */
212
    public function actionUpdate($id)
213
    {
214
        $model = $this->findViewableModel($id, Yii::$app->user);
215
216
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
217
            return $this->redirect(['view', 'id' => $model->id]);
218
        } else {
219
            return $this->render('update', [
220
                'model' => $model,
221
                'contentTypes' => ContentType::getAllList(false, true),
222
            ]);
223
        }
224
    }
225
226
    /**
227
     * Deletes an existing Content model.
228
     * If deletion is successful, the browser will be redirected to the 'index' page.
229
     *
230
     * @param int $id
231
     *
232
     * @return \yii\web\Response
233
     */
234
    public function actionDelete($id)
235
    {
236
        $model = $this->findViewableModel($id, Yii::$app->user);
237
238
        $model->delete();
239
240
        return $this->smartGoBack();
241
    }
242
243
    /**
244
     * Renders specific content for preview.
245
     *
246
     * @param int $id content id
247
     *
248
     * @return string HTML render
249
     */
250
    public function actionPreview($id)
251
    {
252
        $model = $this->findViewableModel($id, Yii::$app->user);
253
254
        return $this->renderPartial('preview', [
255
            'type' => $model->type,
256
            'data' => $model->getData(),
257
        ]);
258
    }
259
260
    /**
261
     * Enables or disable a specific content.
262
     *
263
     * @param int $id content id
264
     *
265
     * @return \yii\web\Response
266
     */
267
    public function actionToggle($id)
268
    {
269
        $model = $this->findViewableModel($id, Yii::$app->user);
270
271
        $model->enabled = !$model->enabled;
272
273
        $model->save();
274
275
        return $this->smartGoBack();
276
    }
277
278
    /**
279
     * Finds the Content model based on its primary key value.
280
     * If the model is not found, a 404 HTTP exception will be thrown.
281
     * If the user has not enough rights, a 403 HTTP exception will be thrown.
282
     *
283
     * @param int           $id
284
     * @param \yii\web\User $user
285
     *
286
     * @return Content the loaded model
287
     *
288
     * @throws NotFoundHttpException  if the model cannot be found
289
     * @throws ForbiddenHttpException if the model cannot be accessed
290
     */
291
    protected function findViewableModel($id, $user)
292
    {
293
        $model = $this->findModel($id);
294
        if ($model->canView($user)) {
295
            return $model;
296
        }
297
298
        throw new \yii\web\ForbiddenHttpException(Yii::t('app', 'You do not have enough rights to view this content.'));
299
    }
300
301
    /**
302
     * Finds the Content model based on its primary key value.
303
     * If the model is not found, a 404 HTTP exception will be thrown.
304
     *
305
     * @param int $id
306
     *
307
     * @return Content the loaded model
308
     *
309
     * @throws NotFoundHttpException if the model cannot be found
310
     */
311 View Code Duplication
    protected function findModel($id)
312
    {
313
        if (($model = Content::findOne($id)) !== null) {
0 ignored issues
show
Bug Compatibility introduced by
The expression \app\models\Content::findOne($id); of type yii\db\ActiveRecordInterface|array|null adds the type array to the return on line 314 which is incompatible with the return type documented by app\controllers\ContentController::findModel of type app\models\Content.
Loading history...
314
            return $model;
315
        } else {
316
            throw new NotFoundHttpException(Yii::t('app', 'The requested content does not exist.'));
317
        }
318
    }
319
}
320