CreateAction.php 1.9 KB

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