1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @author Anton Tuyakhov <[email protected]> |
4
|
|
|
*/ |
5
|
|
|
|
6
|
|
|
namespace tuyakhov\jsonapi\actions; |
7
|
|
|
|
8
|
|
|
use Yii; |
9
|
|
|
use yii\base\Model; |
10
|
|
|
use yii\helpers\Url; |
11
|
|
|
use yii\web\ServerErrorHttpException; |
12
|
|
|
|
13
|
|
|
class CreateAction extends Action |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @var string the scenario to be assigned to the new model before it is validated and saved. |
17
|
|
|
*/ |
18
|
|
|
public $scenario = Model::SCENARIO_DEFAULT; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @var string the name of the view action. This property is need to create the URL when the model is successfully created. |
22
|
|
|
*/ |
23
|
|
|
public $viewAction = 'view'; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Links the relationships with primary model. |
27
|
|
|
* @var callable |
28
|
|
|
*/ |
29
|
|
|
public $linkRelationships; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Creates a new resource. |
33
|
|
|
* @return \yii\db\ActiveRecordInterface the model newly created |
34
|
|
|
* @throws ServerErrorHttpException if there is any error when creating the model |
35
|
|
|
*/ |
36
|
|
|
public function run() |
37
|
|
|
{ |
38
|
|
|
if ($this->checkAccess) { |
39
|
|
|
call_user_func($this->checkAccess, $this->id); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/* @var $model \yii\db\ActiveRecord */ |
43
|
|
|
$model = new $this->modelClass([ |
44
|
|
|
'scenario' => $this->scenario, |
45
|
|
|
]); |
46
|
|
|
|
47
|
|
|
$request = Yii::$app->getRequest(); |
48
|
|
|
$model->load($request->getBodyParams()); |
49
|
|
|
if ($model->save()) { |
50
|
|
|
$this->linkRelationships($model, $request->getBodyParam('relationships')); |
51
|
|
|
$response = Yii::$app->getResponse(); |
52
|
|
|
$response->setStatusCode(201); |
53
|
|
|
$id = implode(',', array_values($model->getPrimaryKey(true))); |
54
|
|
|
$response->getHeaders()->set('Location', Url::toRoute([$this->viewAction, 'id' => $id], true)); |
55
|
|
|
} elseif (!$model->hasErrors()) { |
56
|
|
|
throw new ServerErrorHttpException('Failed to create the object for unknown reason.'); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
return $model; |
60
|
|
|
} |
61
|
|
|
} |