WidgetController::actionCreate()   D
last analyzed

Complexity

Conditions 14
Paths 64

Size

Total Lines 83
Code Lines 48

Duplication

Lines 30
Ratio 36.14 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 30
loc 83
rs 4.9516
cc 14
eloc 48
nc 64
nop 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Widget;
12
use Yii;
13
use yii\filters\AccessControl;
14
use yii\filters\VerbFilter;
15
use yii\helpers\ArrayHelper;
16
use yii\helpers\FileHelper;
17
use yii\web\Controller;
18
use yii\web\NotFoundHttpException;
19
use yii\web\UploadedFile;
20
21
/**
22
 * WidgetController, controlling the actions for Widget model.
23
 *
24
 * @author Agiel K. Saputra <[email protected]>
25
 * @since 0.2.0
26
 */
27
class WidgetController extends Controller
28
{
29
    /**
30
     * @var string Path to widget directory.
31
     */
32
    private $_dir;
33
34
    /**
35
     * @var string Path to temporary directory of widget.
36
     */
37
    private $_tmp;
38
39
    /**
40
     * @inheritdoc
41
     */
42 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...
43
    {
44
        return [
45
            'access' => [
46
                'class' => AccessControl::className(),
47
                'rules' => [
48
                    [
49
                        'actions' => [
50
                            'index',
51
                            'create',
52
                            'delete',
53
                            'ajax-activate',
54
                            'ajax-update',
55
                            'ajax-delete',
56
                            'ajax-save-order',
57
                        ],
58
                        'allow'   => true,
59
                        'roles'   => ['administrator'],
60
                    ],
61
                ],
62
            ],
63
            'verbs'  => [
64
                'class'   => VerbFilter::className(),
65
                'actions' => [
66
                    'delete' => ['post'],
67
                    'ajax-activate' => ['post'],
68
                    'ajax-update'   => ['post'],
69
                    'ajax-delete'   => ['post'],
70
                ],
71
            ],
72
        ];
73
    }
74
75
    /**
76
     * Scan widget directory to get list of all available widgets and list all active widgets.
77
     *
78
     * @return mixed
79
     */
80
    public function actionIndex()
81
    {
82
        $config = [];
83
        $active = [];
84
        $available = [];
85
        $spaces = ArrayHelper::getValue(Yii::$app->params, 'widget', []);
86
87
        if (!is_dir($this->_dir)) {
88
            FileHelper::createDirectory($this->_dir, 0755);
89
        }
90
91
        foreach (scandir($this->_dir) as $widget) {
92
            if (is_dir($this->_dir . $widget) && $widget !== '.' && $widget !== '..') {
93
                $configPath = $this->_dir . $widget . '/config/main.php';
94
                if (is_file($configPath)) {
95
                    $config = require($configPath);
96
                    $config['directory'] = $widget;
97
                }
98
                $available[$widget] = $config;
99
            }
100
        }
101
102
        foreach ($spaces as $space) {
103
            $model = Widget::find()
104
                ->where(['location' => $space['location']])
105
                ->orderBy(['order' => SORT_ASC])
106
                ->all();
107
            $active[$space['location']] = $model;
108
        }
109
110
        return $this->render('index', [
111
            'active' => $active,
112
            'available' => $available,
113
            'spaces' => $spaces,
114
        ]);
115
    }
116
117
    /**
118
     * Register new widget.
119
     * Widget zip uploaded to temporary directory and extracted there.
120
     * Check the widget directory and move the first directory of the extracted widget.
121
     * If the widget configuration is valid, save the widget, if not remove the widget.
122
     * If registration is successful, the browser will be redirected to the 'index' page.
123
     *
124
     * @return mixed
125
     */
126
    public function actionCreate()
127
    {
128
        $errors = [];
129
        $model = new Widget(['scenario' => 'upload']);
130
131
        if (!is_dir($this->_tmp)) {
132
            FileHelper::createDirectory($this->_tmp, 0755);
133
        }
134
135
        if (!is_dir($this->_dir)) {
136
            FileHelper::createDirectory($this->_dir, 0755);
137
        }
138
139
        if (($model->file = UploadedFile::getInstance($model, 'file')) && $model->validate(['file'])) {
140
            $tmpPath = $this->_tmp . $model->file->name;
141
142 View Code Duplication
            if (!$model->file->saveAs($tmpPath)) {
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...
143
                return $this->render('create', [
144
                    'model' => $model,
145
                    'errors' => [Yii::t('writesdown', 'Failed to move uploaded file')],
146
                ]);
147
            }
148
149
            $zipArchive = new \ZipArchive();
150
            $zipArchive->open($tmpPath);
151
152 View Code Duplication
            if (!$zipArchive->extractTo($this->_tmp)) {
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...
153
                $zipArchive->close();
154
                FileHelper::removeDirectory($this->_tmp);
155
156
                return $this->render('create', [
157
                    'model' => $model,
158
                    'errors' => [Yii::t('writesdown', 'Failed to extract file.')],
159
                ]);
160
            }
161
162
            $baseDir = substr($zipArchive->getNameIndex(0), 0, strpos($zipArchive->getNameIndex(0), '/'));
163
            $zipArchive->close();
164
            $configPath = $this->_tmp . $baseDir . '/config/main.php';
165
166 View Code Duplication
            if (!is_file($configPath)) {
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...
167
                FileHelper::removeDirectory($this->_tmp);
168
169
                return $this->render('create', [
170
                    'model' => $model,
171
                    'errors' => [Yii::t('writesdown', 'File configuration does not exist.')],
172
                ]);
173
            }
174
175
            $config = require($configPath);
176
177
            if (is_dir($this->_dir . $baseDir)) {
178
                $errors['dirExist'] = Yii::t('writesdown', 'Widget with the same directory already exist.');
179
            } else {
180
                rename($this->_tmp . $baseDir, $this->_dir . $baseDir);
181
            }
182
183
            FileHelper::removeDirectory($this->_tmp);
184
185
            if (!isset($config['title'])
186
                || !(isset($config['config']['class']) && class_exists($config['config']['class']))
187
            ) {
188
                $errors[] = Yii::t('writesdown', 'Invalid configuration.');
189
            }
190
191
            if (!$errors) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $errors 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...
192
                Yii::$app->getSession()->setFlash('success', Yii::t('writesdown', 'Widget successfully installed.'));
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...
193
194
                return $this->redirect(['index']);
195 View Code Duplication
            } else {
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...
196
                if (!ArrayHelper::getValue($errors, 'dirExist')) {
197
                    FileHelper::removeDirectory($this->_dir . $baseDir);
198
                }
199
200
                $errors = ArrayHelper::merge($errors, $model->getFirstErrors());
201
            }
202
        }
203
204
        return $this->render('create', [
205
            'model' => $model,
206
            'errors' => $errors,
207
        ]);
208
    }
209
210
    /**
211
     * Delete widget and activated widgets.
212
     *
213
     * @param $id string
214
     *
215
     * @return \yii\web\Response
216
     */
217
    public function actionDelete($id)
218
    {
219
        FileHelper::removeDirectory($this->_dir . $id);
220
        Widget::deleteAll(['directory' => $id]);
221
222
        return $this->redirect(['index']);
223
    }
224
225
    /**
226
     * Activated widget via ajax
227
     *
228
     * @param $id string
229
     *
230
     * @return null|string
231
     */
232
    public function actionAjaxActivate($id)
233
    {
234
        $model = new Widget(['scenario' => 'activate']);
235
        if ($model->load(Yii::$app->request->post())) {
236
            $configPath = $this->_dir . $id . '/config/main.php';
237
            $config = require($configPath);
238
239
            // Set attribute of model
240
            $model->setAttributes($config);
241
            $model->setAttributes([
242
                'directory' => $id,
243
                'config' => Json::encode($model->config),
244
                'order' => Widget::find()->where(['location' => $model->location])->count(),
245
            ]);
246
247
            if ($model->save()) {
248
                return $this->renderPartial('_active', [
249
                    'active' => $model,
250
                    'available' => [$model->directory => $config],
251
                ]);
252
            }
253
        }
254
255
        return null;
256
    }
257
258
    /**
259
     * Update activated widget via ajax.
260
     *
261
     * @param $id integer
262
     */
263
    public function actionAjaxUpdate($id)
264
    {
265
        $model = $this->findModel($id);
266
267
        if ($model->load(Yii::$app->request->post())) {
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...
268
            $model->config = Json::encode($model->config);
269
            $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...
270
        }
271
    }
272
273
    /**
274
     * Delete active widget via ajax.
275
     *
276
     * @param $id integer
277
     */
278
    public function actionAjaxDelete($id)
279
    {
280
        $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...
281
    }
282
283
    /**
284
     * Save order for widget.
285
     */
286
    public function actionAjaxSaveOrder()
287
    {
288
        if ($ids = Yii::$app->request->post('ids')) {
289
            foreach ($ids as $order => $id) {
290
                $this->findModel($id)->updateAttributes(['order' => $order]);
0 ignored issues
show
Bug introduced by
The method updateAttributes 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...
291
            }
292
        }
293
    }
294
295
    /**
296
     * @inheritdoc
297
     */
298
    public function beforeAction($action)
299
    {
300
        if (in_array($this->action->id, ['ajax-activate', 'ajax-update', 'ajax-delete', 'ajax-save-order'])) {
301
            $this->enableCsrfValidation = false;
302
        }
303
304 View Code Duplication
        if (parent::beforeAction($action)) {
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...
305
            $this->_dir = Yii::getAlias('@widgets/');
0 ignored issues
show
Documentation Bug introduced by
It seems like \Yii::getAlias('@widgets/') can also be of type boolean. However, the property $_dir is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
306
            $this->_tmp = Yii::getAlias('@common/tmp/widgets/');
0 ignored issues
show
Documentation Bug introduced by
It seems like \Yii::getAlias('@common/tmp/widgets/') can also be of type boolean. However, the property $_tmp is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
307
308
            return true;
309
        }
310
311
        return false;
312
    }
313
314
    /**
315
     * Finds the Widget model based on its primary key value.
316
     * If the model is not found, a 404 HTTP exception will be thrown.
317
     *
318
     * @param integer $id
319
     *
320
     * @return Widget the loaded model
321
     * @throws NotFoundHttpException if the model cannot be found
322
     */
323
    protected function findModel($id)
324
    {
325
        if (($model = Widget::findOne($id)) !== null) {
326
            return $model;
327
        }
328
329
        throw new NotFoundHttpException('The requested page does not exist.');
330
    }
331
}
332