Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

62 lines
1.8KB

  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. * @author Qiang Xue <qiang.xue@gmail.com>
  16. * @since 2.0
  17. */
  18. class CreateAction extends Action
  19. {
  20. /**
  21. * @var string the scenario to be assigned to the new model before it is validated and saved.
  22. */
  23. public $scenario = Model::SCENARIO_DEFAULT;
  24. /**
  25. * @var string the name of the view action. This property is need to create the URL when the model is successfully created.
  26. */
  27. public $viewAction = 'view';
  28. /**
  29. * Creates a new model.
  30. * @return \yii\db\ActiveRecordInterface the model newly created
  31. * @throws ServerErrorHttpException if there is any error when creating the model
  32. */
  33. public function run()
  34. {
  35. if ($this->checkAccess) {
  36. call_user_func($this->checkAccess, $this->id);
  37. }
  38. /* @var $model \yii\db\ActiveRecord */
  39. $model = new $this->modelClass([
  40. 'scenario' => $this->scenario,
  41. ]);
  42. $model->load(Yii::$app->getRequest()->getBodyParams(), '');
  43. if ($model->save()) {
  44. $response = Yii::$app->getResponse();
  45. $response->setStatusCode(201);
  46. $id = implode(',', array_values($model->getPrimaryKey(true)));
  47. $response->getHeaders()->set('Location', Url::toRoute([$this->viewAction, 'id' => $id], true));
  48. } elseif (!$model->hasErrors()) {
  49. throw new ServerErrorHttpException('Failed to create the object for unknown reason.');
  50. }
  51. return $model;
  52. }
  53. }