Completed
Pull Request — master (#5)
by Angel
05:01
created

Create   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Test Coverage

Coverage 89.47%

Importance

Changes 0
Metric Value
eloc 20
dl 0
loc 39
ccs 17
cts 19
cp 0.8947
rs 10
c 0
b 0
f 0
wmc 3

1 Method

Rating   Name   Duplication   Size   Complexity  
A run() 0 25 3
1
<?php
2
3
namespace roaresearch\yii2\roa\actions;
4
5
use Yii;
6
use yii\{base\Model, web\ServerErrorHttpException};
7
8
/**
9
 * Action to create a record.
10
 * @author Angel (Faryshta) Guevara <[email protected]>
11
 */
12
class Create extends Action
13
{
14 1
    use LoadFileTrait;
15
16
    /**
17
     * @var string the scenario to be assigned to the new model before it is validated and saved.
18
     */
19
    public $scenario = Model::SCENARIO_DEFAULT;
20
21
    /**
22
     * Creates a new model.
23
     * @return \yii\db\ActiveRecordInterface the model newly created
24
     * @throws ServerErrorHttpException if there is any error when creating the model
25
     */
26 8
    public function run()
27
    {
28 8
        $request = Yii::$app->getRequest();
29 8
        $modelClass = $this->modelClass;
30
        /* @var $model \yii\db\ActiveRecordInterface */
31 8
        $model = new $modelClass([
32 8
            'scenario' => $this->scenario,
33
        ]);
34 8
        $model->load(
35 8
            $request->getQueryParams() + $request->getBodyParams(),
36 8
            ''
37
        );
38 8
        $this->checkAccess($model, $request->getQueryParams());
39 8
        $model->load($this->parseFileAttributes(), '');
40 8
        if ($model->save()) {
41 2
            $response = Yii::$app->getResponse();
42 2
            $response->setStatusCode(201);
43 2
            $response->getHeaders()->set('Location', $model->getSelfLink());
44 6
        } elseif (!$model->hasErrors()) {
45
            throw new ServerErrorHttpException(
46
                'Failed to create the object for unknown reason.'
47
            );
48
        }
49
50 8
        return $model;
51
    }
52
}
53