/** * @return bool * @throws \yii\web\ForbiddenHttpException */ public function beforeRun() { if ($this->needAuthorize && Yii::$app->user->isGuest) { HttpError::the403(); } return parent::beforeRun(); }
/** * @param $id * @return ActiveRecord * @throws \yii\web\NotFoundHttpException */ public function run($id) { /** @var ActiveRecord $model */ $model = new $this->modelClass(); $model = $model->findOne(['id' => $id]); if (empty($model)) { HttpError::the404('Not found'); } return $model; }
/** * @param $id * @throws ServerErrorHttpException * @throws \Exception * @throws \yii\web\NotFoundHttpException */ public function run($id) { /** @var \yii\db\ActiveRecord $model */ $model = new $this->modelClass(); $model = $model->findOne(['id' => $id]); if (empty($model)) { HttpError::the404('Not found'); } if ($model->delete() === false) { throw new ServerErrorHttpException('Failed to delete the object for unknown reason.'); } Yii::$app->getResponse()->setStatusCode(204); }
/** * @param $id * @return \yii\db\ActiveRecord * @throws ServerErrorHttpException * @throws \yii\base\InvalidConfigException * @throws \yii\web\NotFoundHttpException */ public function run($id) { /** @var \yii\db\ActiveRecord $model */ $model = new $this->modelClass(); $model = $model->findOne(['id' => $id]); if (empty($model)) { HttpError::the404('Not found'); } $model->load(Yii::$app->getRequest()->getBodyParams(), ''); if ($model->save() === false && !$model->hasErrors()) { throw new ServerErrorHttpException('Failed to update the object for unknown reason.'); } return $model; }
/** * @param int $offset * @param int $limit * @return array */ public function run($offset = 0, $limit = 10) { /** @var \platx\rest\SearchForm $searchForm */ $searchForm = new $this->searchFormClass(); $get = Yii::$app->request->get(); $query = $searchForm->buildQuery($get); if (!$query) { return HttpError::validateError('Validation error', $searchForm->errors); } $queryCount = clone $query; $countAll = (int) $queryCount->limit(-1)->offset(-1)->orderBy([])->count('*'); $query->offset($offset); if ($limit) { $query->limit($limit); } $models = $query->all(); $models = (new Serializer())->serializeModels($models); $countCurrent = count($models); $result = ['offset' => $offset, 'limit' => $limit, 'count_all' => (int) $countAll, 'count_current' => $countCurrent, 'items' => $models]; return $result; }