ScreenTemplateController   A
last analyzed

Complexity

Total Complexity 35

Size/Duplication

Total Lines 318
Duplicated Lines 18.87 %

Coupling/Cohesion

Components 1
Dependencies 10

Importance

Changes 0
Metric Value
wmc 35
lcom 1
cbo 10
dl 60
loc 318
rs 9.6
c 0
b 0
f 0

14 Methods

Rating   Name   Duplication   Size   Complexity  
A behaviors() 0 18 1
A actionIndex() 10 10 1
A actionView() 0 13 2
A actionCreate() 13 13 3
A actionUpdate() 13 13 3
A actionDelete() 0 6 1
A findModel() 8 8 2
A actionAddField() 5 17 2
A actionGetField() 5 12 2
B actionEditField() 0 38 7
A actionSetFieldPos() 3 21 5
A actionDeleteField() 3 11 3
A backgroundsArray() 0 15 2
A randf() 0 4 1

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\ContentType;
7
use app\models\ScreenTemplate;
8
use app\models\Field;
9
use app\models\TemplateBackground;
10
use yii\data\ActiveDataProvider;
11
use yii\helpers\Url;
12
use yii\web\NotFoundHttpException;
13
use yii\filters\VerbFilter;
14
use yii\filters\AccessControl;
15
16
/**
17
 * ScreentemplateController implements the CRUD actions for ScreenTemplate model.
18
 */
19
class ScreenTemplateController extends BaseController
20
{
21
    /**
22
     * {@inheritdoc}
23
     */
24
    public function behaviors()
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', 'add-field', 'get-field', 'edit-field', 'set-field-pos', 'delete-field', 'create', 'update', 'delete'],
36
                'rules' => [
37
                    ['allow' => true, 'actions' => ['index', 'view', 'add-field', 'get-field', 'edit-field', 'set-field-pos', 'delete-field', 'create', 'update', 'delete'], 'roles' => ['setTemplates']],
38
                ],
39
            ],
40
        ];
41
    }
42
43
    /**
44
     * Lists all ScreenTemplate models.
45
     *
46
     * @return string
47
     */
48 View Code Duplication
    public function actionIndex()
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...
49
    {
50
        $dataProvider = new ActiveDataProvider([
51
            'query' => ScreenTemplate::find(),
52
        ]);
53
54
        return $this->render('index', [
55
            'dataProvider' => $dataProvider,
56
        ]);
57
    }
58
59
    /**
60
     * Displays a single ScreenTemplate model.
61
     *
62
     * @param int $id
63
     *
64
     * @return string
65
     */
66
    public function actionView($id)
67
    {
68
        $screenTemplate = $this->findModel($id);
69
70
        return $this->render('view', [
71
            'model' => $screenTemplate,
72
            'background' => $screenTemplate->background ? $screenTemplate->background->uri : null,
73
            'fields' => $screenTemplate->getFields()->with('contentTypes')->asArray()->all(),
74
            'contentTypes' => ContentType::getAllList(),
75
            'setFieldPosUrl' => Url::to([Yii::$app->controller->id . '/set-field-pos', 'id' => '']),
76
            'editFieldUrl' => Url::to([Yii::$app->controller->id . '/edit-field', 'id' => '']),
77
        ]);
78
    }
79
80
    /**
81
     * Creates a new ScreenTemplate model.
82
     * If creation is successful, the browser will be redirected to the 'view' page.
83
     *
84
     * @return \yii\web\Response|string redirect or render
85
     */
86 View Code Duplication
    public function actionCreate()
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...
87
    {
88
        $model = new ScreenTemplate();
89
90
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
91
            return $this->redirect(['view', 'id' => $model->id]);
92
        }
93
94
        return $this->render('create', [
95
            'model' => $model,
96
            'backgrounds' => self::backgroundsArray(),
97
        ]);
98
    }
99
100
    /**
101
     * Updates an existing ScreenTemplate model.
102
     * If update is successful, the browser will be redirected to the 'view' page.
103
     *
104
     * @param int $id
105
     *
106
     * @return \yii\web\Response|string redirect or render
107
     */
108 View Code Duplication
    public function actionUpdate($id)
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...
109
    {
110
        $model = $this->findModel($id);
111
112
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
113
            return $this->redirect(['view', 'id' => $model->id]);
114
        }
115
116
        return $this->render('update', [
117
            'model' => $model,
118
            'backgrounds' => self::backgroundsArray(),
119
        ]);
120
    }
121
122
    /**
123
     * Deletes an existing ScreenTemplate model.
124
     * If deletion is successful, the browser will be redirected to the 'index' page.
125
     *
126
     * @param int $id
127
     *
128
     * @return \yii\web\Response
129
     */
130
    public function actionDelete($id)
131
    {
132
        $this->findModel($id)->delete();
133
134
        return $this->redirect(['index']);
135
    }
136
137
    /**
138
     * Finds the ScreenTemplate model based on its primary key value.
139
     * If the model is not found, a 404 HTTP exception will be thrown.
140
     *
141
     * @param int $id
142
     *
143
     * @return ScreenTemplate the loaded model
144
     *
145
     * @throws NotFoundHttpException if the model cannot be found
146
     */
147 View Code Duplication
    protected function findModel($id)
148
    {
149
        if (($model = ScreenTemplate::findOne($id)) !== null) {
0 ignored issues
show
Bug Compatibility introduced by
The expression \app\models\ScreenTemplate::findOne($id); of type yii\db\ActiveRecordInterface|array|null adds the type array to the return on line 150 which is incompatible with the return type documented by app\controllers\ScreenTe...teController::findModel of type app\models\ScreenTemplate.
Loading history...
150
            return $model;
151
        } else {
152
            throw new NotFoundHttpException(Yii::t('app', 'The requested template does not exist.'));
153
        }
154
    }
155
156
    /**
157
     * Create a field and save it.
158
     *
159
     * @api
160
     *
161
     * @param int $templateId
162
     *
163
     * @return string json status
164
     */
165
    public function actionAddField($templateId)
166
    {
167
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
168
169
        $field = new Field();
170
        $field->template_id = $templateId;
171
        $field->x1 = self::randf(0.1, 0.4);
172
        $field->y1 = self::randf(0.1, 0.4);
173
        $field->x2 = self::randf($field->x1, 0.8);
174
        $field->y2 = self::randf($field->y1, 0.8);
175
176 View Code Duplication
        if ($field->save()) {
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...
177
            return ['success' => true, 'field' => $field];
178
        } else {
179
            return ['success' => false, 'message' => Yii::t('app', 'Failed to insert new field')];
180
        }
181
    }
182
183
    /**
184
     * Retrieve a field spec.
185
     *
186
     * @api
187
     *
188
     * @param int $id field id
189
     *
190
     * @return string json field
191
     */
192
    public function actionGetField($id)
193
    {
194
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
195
196
        $field = Field::find()->where(['id' => $id])->with('contentTypes')->one();
197
198 View Code Duplication
        if ($field === null) {
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...
199
            return ['success' => false, 'message' => Yii::t('app', 'Field not found')];
200
        } else {
201
            return ['success' => true, 'field' => $field, 'contentTypes' => $field->contentTypes];
202
        }
203
    }
204
205
    /**
206
     * Read POST data and update field, or display AJAX popup form.
207
     *
208
     * @param int $id field id
209
     *
210
     * @return string
211
     */
212
    public function actionEditField($id)
213
    {
214
        $field = Field::find()->where(['id' => $id])->with('contentTypes')->one();
215
        if ($field === null) {
216
            return;
217
        }
218
219
        if ($field->load(Yii::$app->request->post())) {
220
            $newTypeIds = Yii::$app->request->post($field->formName())['contentTypes'];
221
            if (!is_array($newTypeIds)) {
222
                $newTypeIds = [];
223
            }
224
            $oldTypeIds = array_map(function ($c) {
225
                return $c->id;
226
            }, $field->contentTypes);
227
228
            $unlink = array_diff($oldTypeIds, $newTypeIds);
229
            $unlinkModels = ContentType::find()->where(['id' => $unlink])->all();
230
            foreach ($unlinkModels as $u) {
231
                $field->unlink('contentTypes', $u, true);
232
            }
233
            $link = array_diff($newTypeIds, $oldTypeIds);
234
            $linkModels = ContentType::find()->where(['id' => $link])->all();
235
            foreach ($linkModels as $l) {
236
                $field->link('contentTypes', $l);
237
            }
238
239
            if ($field->save()) {
240
                return '';
241
            }
242
        }
243
244
        return $this->renderAjax('editfield', [
245
            'field' => $field,
246
            'contentTypesArray' => ContentType::getAllList(),
247
            'selfContentIds' => ContentType::getAllList(true),
248
        ]);
249
    }
250
251
    /**
252
     * Update field position.
253
     *
254
     * @api
255
     *
256
     * @param int $id field id
257
     *
258
     * @return string json status
259
     */
260
    public function actionSetFieldPos($id = null)
261
    {
262
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
263
264
        if ($id !== null) {
265
            $field = Field::find()->where(['id' => $id])->one();
266 View Code Duplication
            if ($field === null) {
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...
267
                return ['success' => false, 'message' => Yii::t('app', 'No such field')];
268
            }
269
        } else {
270
            $field = new Field();
271
        }
272
273
        if ($field->load(Yii::$app->request->post())) {
274
            if ($field->save()) {
275
                return ['success' => true, 'id' => $field->id];
276
            }
277
        }
278
279
        return ['success' => false, 'message' => $field->errors];
280
    }
281
282
    /**
283
     * Delete a field.
284
     *
285
     * @api
286
     *
287
     * @param int $id field id
288
     *
289
     * @return string json status
290
     */
291
    public function actionDeleteField($id)
292
    {
293
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
294
295
        $field = Field::find()->where(['id' => $id])->with('contentTypes')->one();
296 View Code Duplication
        if ($field === null || $field->delete() === false) {
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...
297
            return ['success' => false, 'message' => Yii::t('app', 'Deletion failed')];
298
        }
299
300
        return ['success' => true];
301
    }
302
303
    /**
304
     * Builds an array of backgrounds usable in view.
305
     *
306
     * @return string[] backgrounds
307
     */
308
    public static function backgroundsArray()
309
    {
310
        $bgs = TemplateBackground::find()->all();
311
312
        $array = [];
313
        foreach ($bgs as $bg) {
314
            $array[$bg->id] = [
315
                'id' => $bg->id,
316
                'name' => $bg->name,
317
                'uri' => $bg->uri,
318
            ];
319
        }
320
321
        return $array;
322
    }
323
324
    /**
325
     * Custom min/max float rand.
326
     *
327
     * @param float $min
328
     * @param float $max
329
     *
330
     * @return float random float
331
     */
332
    public static function randf($min = 0.0, $max = 1.0)
333
    {
334
        return mt_rand($min * mt_getrandmax(), $max * mt_getrandmax()) / mt_getrandmax();
335
    }
336
}
337