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

SliderController   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 249
Duplicated Lines 14.06 %

Coupling/Cohesion

Components 1
Dependencies 5
Metric Value
wmc 32
lcom 1
cbo 5
dl 35
loc 249
rs 9.6

9 Methods

Rating   Name   Duplication   Size   Complexity  
A behaviors() 14 14 1
A actionIndex() 0 18 1
C actionUpdate() 21 54 10
A actionNewSlide() 0 11 1
C actionUpdateSlide() 0 41 8
A actionDeleteSlide() 0 7 1
C actionUploadSlide() 0 43 7
A actionDelete() 0 6 1
A findModel() 0 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\backend\controllers;
4
5
use app\backend\traits\BackendRedirect;
6
use app\models\Slide;
7
use app\slider\BaseSliderEditModel;
8
use Imagine\Image\ManipulatorInterface;
9
use kartik\icons\Icon;
10
use Yii;
11
use app\models\Slider;
12
use app\components\SearchModel;
13
use yii\filters\AccessControl;
14
use yii\web\BadRequestHttpException;
15
use yii\web\Controller;
16
use yii\web\HttpException;
17
use yii\web\NotFoundHttpException;
18
use yii\web\Response;
19
use yii\web\UploadedFile;
20
21
/**
22
 * SliderController implements the CRUD actions for Slider model.
23
 */
24
class SliderController extends Controller
25
{
26
    use BackendRedirect;
27
    /**
28
     * @inheritdoc
29
     */
30 View Code Duplication
    public function behaviors()
31
    {
32
        return [
33
            'access' => [
34
                'class' => AccessControl::className(),
35
                'rules' => [
36
                    [
37
                        'allow' => true,
38
                        'roles' => ['content manage'],
39
                    ],
40
                ],
41
            ],
42
        ];
43
    }
44
45
46
    /**
47
     * Lists all Slider models.
48
     * @return mixed
49
     */
50
    public function actionIndex()
51
    {
52
        $searchModel = new SearchModel(
53
            [
54
                'model' => Slider::className(),
55
                'partialMatchAttributes' => ['name'],
56
                'scenario' => 'default',
57
            ]
58
        );
59
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
60
        return $this->render(
61
            'index',
62
            [
63
                'searchModel' => $searchModel,
64
                'dataProvider' => $dataProvider,
65
            ]
66
        );
67
    }
68
69
    /**
70
     * Updates an existing Slider model.
71
     * If update is successful, the browser will be redirected to the 'view' page.
72
     * @param null|string $id
73
     * @return mixed
74
     */
75
    public function actionUpdate($id = null)
0 ignored issues
show
Coding Style introduced by
actionUpdate uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
76
    {
77
        $abstractModel = new BaseSliderEditModel();
78
79
        if (is_null($id)) {
80
            $model = new Slider;
81
            $model->loadDefaultValues();
82 View Code Duplication
        } else {
83
            $model = $this->findModel($id);
84
            if ($model->handler() !== null) {
85
                $abstractModel = Yii::createObject(['class'=>$model->handler()->edit_model]);
86
                if (!empty($model->params)) {
87
                    $abstractModel->unserialize($model->params);
88
                }
89
            }
90
        }
91
92
        $post = Yii::$app->request->post();
93
94
        if ($model->load($post) && $model->validate()) {
95 View Code Duplication
            if ($model->handler() !== null) {
96
                $abstractModel = Yii::createObject(['class'=>$model->handler()->edit_model]);
97
                if (!empty($model->params)) {
98
                    $abstractModel->unserialize($model->params);
99
                }
100
            }
101
            $abstractModel->load($post);
102
            if ($abstractModel->validate()) {
103
                $model->params = $abstractModel->serialize();
104 View Code Duplication
                if ($model->save()) {
105
                    return $this->redirectUser($model->id, true, 'index', 'update');
106
107
                } else {
108
                    Yii::$app->session->setFlash('error', Yii::t('app', 'Cannot save data'));
109
                }
110
            } else {
111
                Yii::$app->session->setFlash('error', Yii::t('app', 'Cannot save data'));
112
            }
113
        }
114
115
        $searchModel = new Slide();
116
        $searchModel->slider_id = $model->id;
117
        $dataProvider = $searchModel->search($_GET);
118
119
        return $this->render(
120
            'update',
121
            [
122
                'model' => $model,
123
                'abstractModel' => $abstractModel,
124
                'dataProvider' => $dataProvider,
125
                'searchModel' => $searchModel,
126
            ]
127
        );
128
    }
129
130
    /**
131
     * @param integer $slider_id
132
     */
133
    public function actionNewSlide($slider_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...
134
    {
135
        Yii::$app->response->format = Response::FORMAT_JSON;
136
        $slider = $this->findModel($slider_id);
137
        $model = new Slide();
138
        $model->slider_id = $slider->id;
139
        $model->active = 0;
140
        $model->sort_order = count($slider->getSlides());
141
        $model->save();
142
        return $this->redirect(['update', 'id' => $slider_id]);
143
    }
144
145
    /**
146
     * Update slide attributes
147
     * @return array
148
     * @throws \yii\web\BadRequestHttpException
149
     */
150
    public function actionUpdateSlide()
151
    {
152
        Yii::$app->response->format = Response::FORMAT_JSON;
153
        $post = Yii::$app->request->post();
154
155
        if (!isset($post['editableIndex'], $post['editableKey'])) {
156
            throw new BadRequestHttpException;
157
        }
158
        $id = $post['editableKey'];
159
        /** @var Slide $model */
160
        $model = Slide::findOne($id);
161
        if ($model === null) {
162
            throw new BadRequestHttpException;
163
        }
164
        $index = $post['editableIndex'];
165
        if (!is_array($post['Slide'][$index])) {
166
            throw new BadRequestHttpException;
167
        }
168
        if (count($post['Slide'][$index])===0) {
169
            throw new BadRequestHttpException;
170
        }
171
172
        $modifiedAttribute = array_keys($post['Slide'][$index])[0];
173
174
        $model->setAttributes($post['Slide'][$index]);
175
176
177
        if (!$model->save()) {
178
            return [
179
                'message' => Yii::t('app', 'Cannot save object'),
180
            ];
181
        }
182
183
        if ($modifiedAttribute === 'active') {
184
            $model->active ? Icon::show('check txt-color-green') : Icon::show('times txt-color-red');
185
        }
186
187
        return [
188
            'output' => $model->getAttribute($modifiedAttribute),
189
        ];
190
    }
191
192
    public function actionDeleteSlide($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...
193
    {
194
        $slide = Slide::findOne($id);
195
        $slider_id = $slide->slider_id;
196
        $slide->delete();
197
        return $this->redirect(['update', 'id'=>$slider_id]);
198
    }
199
200
    public function actionUploadSlide()
0 ignored issues
show
Coding Style introduced by
actionUploadSlide uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
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...
201
    {
202
        if (!isset($_POST['slide_id'], $_POST['attribute'], $_POST['slider_id'])) {
203
            throw new BadRequestHttpException();
204
        }
205
206
        $model = Slider::findById($_POST['slider_id']);
207
        $slide = Slide::findOne($_POST['slide_id']);
208
        if ($model === null || $slide === null) {
209
            throw new NotFoundHttpException;
210
        }
211
212
        $file = UploadedFile::getInstanceByName('file');
213
        if ($file === null) {
214
            throw new HttpException(500, "Upload file error");
215
        }
216
        if ($file->hasError) {
217
            throw new HttpException(500, 'Upload error');
218
        }
219
220
        $fileName = $file->name;
221
        $uploadDir = Yii::getAlias(Yii::$app->getModule('core')->fileUploadPath);
222
        $fn = $uploadDir . $fileName;
223
        if (file_exists($fn)) {
224
            $fileName = $file->baseName . '-' . uniqid() . '.' . $file->extension;
225
            $fn = $uploadDir . $fileName;
226
        }
227
228
229
        $file->saveAs($fn);
230
231
        $image = \yii\imagine\Image::thumbnail($uploadDir . $fileName,
232
            $model->image_width,
233
            $model->image_height,
234
            ManipulatorInterface::THUMBNAIL_INSET
235
        );
236
        $image->save($uploadDir . 'small-' . $fileName, ['quality'=>95]);
237
238
        $slide->setAttribute($_POST['attribute'], str_replace(Yii::getAlias('@webroot'), '', $uploadDir) . 'small-' . $fileName);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 129 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
239
        $slide->save();
240
241
        return $this->redirect(['update', 'id' => $model->id]);
242
    }
243
244
    /**
245
     * Deletes an existing Slider model.
246
     * If deletion is successful, the browser will be redirected to the 'index' page.
247
     * @param string $id
248
     * @return mixed
249
     */
250
    public function actionDelete($id)
251
    {
252
        $this->findModel($id)->delete();
253
254
        return $this->redirect(['index']);
255
    }
256
257
    /**
258
     * Finds the Slider model based on its primary key value.
259
     * If the model is not found, a 404 HTTP exception will be thrown.
260
     * @param string $id
261
     * @return Slider the loaded model
262
     * @throws NotFoundHttpException if the model cannot be found
263
     */
264
    protected function findModel($id)
265
    {
266
        if (($model = Slider::findById($id)) !== null) {
267
            return $model;
268
        } else {
269
            throw new NotFoundHttpException('The requested page does not exist.');
270
        }
271
    }
272
}