CreateAction.php 1.79 KB
Newer Older
Qiang Xue committed
1 2 3 4 5 6 7 8 9 10
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\rest;

use Yii;
Qiang Xue committed
11
use yii\base\Model;
Antonio Ramirez committed
12
use yii\helpers\Url;
13
use yii\web\ServerErrorHttpException;
Qiang Xue committed
14 15 16 17 18 19 20 21 22

/**
 * CreateAction implements the API endpoint for creating a new model from the given data.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class CreateAction extends Action
{
23 24 25 26 27
    /**
     * @var string the scenario to be assigned to the new model before it is validated and saved.
     */
    public $scenario = Model::SCENARIO_DEFAULT;
    /**
28
     * @var string the name of the view action. This property is need to create the URL when the model is successfully created.
29 30
     */
    public $viewAction = 'view';
Qiang Xue committed
31

32

33 34 35
    /**
     * Creates a new model.
     * @return \yii\db\ActiveRecordInterface the model newly created
36
     * @throws ServerErrorHttpException if there is any error when creating the model
37 38 39 40 41 42
     */
    public function run()
    {
        if ($this->checkAccess) {
            call_user_func($this->checkAccess, $this->id);
        }
Qiang Xue committed
43

44
        /* @var $model \yii\db\ActiveRecord */
45 46 47
        $model = new $this->modelClass([
            'scenario' => $this->scenario,
        ]);
Qiang Xue committed
48

49
        $model->load(Yii::$app->getRequest()->getBodyParams(), '');
50
        if ($model->save()) {
51 52 53 54
            $response = Yii::$app->getResponse();
            $response->setStatusCode(201);
            $id = implode(',', array_values($model->getPrimaryKey(true)));
            $response->getHeaders()->set('Location', Url::toRoute([$this->viewAction, 'id' => $id], true));
55 56
        } elseif (!$model->hasErrors()) {
            throw new ServerErrorHttpException('Failed to create the object for unknown reason.');
57
        }
Qiang Xue committed
58

59 60
        return $model;
    }
Qiang Xue committed
61
}