1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @link https://www.yiiframework.com/ |
4
|
|
|
* @copyright Copyright (c) 2008 Yii Software LLC |
5
|
|
|
* @license https://www.yiiframework.com/license/ |
6
|
|
|
*/ |
7
|
|
|
|
8
|
|
|
namespace yii\rest; |
9
|
|
|
|
10
|
|
|
use Yii; |
11
|
|
|
use yii\base\Model; |
12
|
|
|
use yii\helpers\Url; |
13
|
|
|
use yii\web\ServerErrorHttpException; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* CreateAction implements the API endpoint for creating a new model from the given data. |
17
|
|
|
* |
18
|
|
|
* For more details and usage information on CreateAction, see the [guide article on rest controllers](guide:rest-controllers). |
19
|
|
|
* |
20
|
|
|
* @author Qiang Xue <[email protected]> |
21
|
|
|
* @since 2.0 |
22
|
|
|
*/ |
23
|
|
|
class CreateAction extends Action |
24
|
|
|
{ |
25
|
|
|
/** |
26
|
|
|
* @var string the scenario to be assigned to the new model before it is validated and saved. |
27
|
|
|
*/ |
28
|
|
|
public $scenario = Model::SCENARIO_DEFAULT; |
29
|
|
|
/** |
30
|
|
|
* @var string the name of the view action. This property is needed to create the URL when the model is successfully created. |
31
|
|
|
*/ |
32
|
|
|
public $viewAction = 'view'; |
33
|
|
|
|
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Creates a new model. |
37
|
|
|
* @return \yii\db\ActiveRecordInterface the model newly created |
38
|
|
|
* @throws ServerErrorHttpException if there is any error when creating the model |
39
|
|
|
*/ |
40
|
|
|
public function run() |
41
|
|
|
{ |
42
|
|
|
if ($this->checkAccess) { |
43
|
|
|
call_user_func($this->checkAccess, $this->id); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** @var \yii\db\ActiveRecord $model */ |
47
|
|
|
$model = new $this->modelClass([ |
48
|
|
|
'scenario' => $this->scenario, |
49
|
|
|
]); |
50
|
|
|
|
51
|
|
|
$model->load(Yii::$app->getRequest()->getBodyParams(), ''); |
|
|
|
|
52
|
|
|
if ($model->save()) { |
53
|
|
|
$response = Yii::$app->getResponse(); |
54
|
|
|
$response->setStatusCode(201); |
|
|
|
|
55
|
|
|
$id = implode(',', $model->getPrimaryKey(true)); |
56
|
|
|
$response->getHeaders()->set('Location', Url::toRoute([$this->viewAction, 'id' => $id], true)); |
|
|
|
|
57
|
|
|
} elseif (!$model->hasErrors()) { |
58
|
|
|
throw new ServerErrorHttpException('Failed to create the object for unknown reason.'); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
return $model; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|