Passed
Push — master ( 62a76c...ad7bbe )
by Matthew
02:02
created

ECreateAction::run()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 13
nc 6
nop 0
dl 0
loc 23
rs 9.8333
c 0
b 0
f 0
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * Date: 2017-12-07
5
 * Time: 03:12
6
 */
7
8
namespace MP\ExtendedApi;
9
10
use Yii;
11
use yii\rest\CreateAction;
12
use yii\base\Model;
13
use yii\helpers\Url;
14
use yii\web\ServerErrorHttpException;
15
16
/**
17
 * Class    ECreateAction
18
 * @package MP\ExtendedApi
19
 * @author  Yarmaliuk Mikhail
20
 * @version 1.0
21
 */
22
class ECreateAction extends CreateAction
23
{
24
    /**
25
     * Creates a new model.
26
     * @return \yii\db\ActiveRecordInterface the model newly created
27
     * @throws ServerErrorHttpException if there is any error when creating the model
28
     */
29
    public function run()
30
    {
31
        /* @var $model \yii\db\ActiveRecord */
32
        $model = new $this->modelClass([
33
            'scenario' => $this->scenario,
34
        ]);
35
36
        $model->load(Yii::$app->getRequest()->getBodyParams(), '');
37
38
        if ($this->checkAccess) {
39
            call_user_func($this->checkAccess, $this->id, $model);
40
        }
41
42
        if ($model->save()) {
43
            $response = Yii::$app->getResponse();
44
            $response->setStatusCode(201);
45
            $id = implode(',', array_values($model->getPrimaryKey(true)));
46
            $response->getHeaders()->set('Location', Url::toRoute([$this->viewAction, 'id' => $id], true));
47
        } elseif (!$model->hasErrors()) {
48
            throw new ServerErrorHttpException('Failed to create the object for unknown reason.');
49
        }
50
51
        return $model;
52
    }
53
}
54