Passed
Pull Request — master (#42)
by Paweł
02:49
created

AccountController::actionCreate()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 26
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 13
nc 6
nop 0
dl 0
loc 26
rs 8.439
c 0
b 0
f 0
1
<?php
2
/**
3
 * Created for IG Monitoring.
4
 * User: jakim <[email protected]>
5
 * Date: 06.05.2018
6
 */
7
8
namespace app\modules\api\v1\controllers;
9
10
11
use app\modules\api\v1\components\ActiveController;
12
use app\modules\api\v1\models\Account;
13
use yii\helpers\Url;
14
use yii\web\ServerErrorHttpException;
15
16
class AccountController extends ActiveController
17
{
18
    public $modelClass = Account::class;
19
20
    public function actions()
21
    {
22
        $actions = parent::actions();
23
        unset($actions['create']);
24
25
        return $actions;
26
    }
27
28
    public function actionCreate()
29
    {
30
        $username = \Yii::$app->request->post('username');
31
32
        $model = Account::findOne(['username' => $username]);
33
34
        if ($model === null) {
35
            $model = new Account();
36
            $model->setScenario($this->createScenario);
37
        }
38
        $isNewRecord = $model->isNewRecord;
39
40
        $model->load(\Yii::$app->getRequest()->getBodyParams(), '');
41
        if ($model->save()) {
42
            $response = \Yii::$app->getResponse();
43
            $response->setStatusCode($isNewRecord ? 201 : 200);
44
45
            // TODO uncomment after create "view" endpoint
46
//            $id = implode(',', array_values($model->getPrimaryKey(true)));
47
//            $response->getHeaders()->set('Location', Url::toRoute(['view', 'id' => $id], true));
48
49
        } elseif (!$model->hasErrors()) {
50
            throw new ServerErrorHttpException('Failed to create the object for unknown reason.');
51
        }
52
53
        return $model;
54
    }
55
}