/** * Multiple creation */ protected function createMany() { if ($this->checkAccess) { call_user_func($this->checkAccess, $this->id); } $items = Yii::$app->getRequest()->getBodyParam($this->manyProperty); if (!is_array($items)) { throw new BadRequestHttpException("{$this->manyProperty} must be array"); } if (count($items) > $this->manyLimit) { throw new BadRequestHttpException("Request Entity Too Large", 413); } /* @var $model \yii\db\ActiveRecord */ $preparedModel = $this->prepareModel(['scenario' => $this->scenario]); $request = Yii::$app->getRequest(); $reload = $request->get('reload'); $collection = new MultistatusCollection(); foreach ($items as $one) { $model = clone $preparedModel; $model->load($one, ''); if ($model->save()) { if ($reload) { $modelClass = $this->modelClass; $model = $modelClass::findOne($model->primaryKey); } } elseif (!$model->hasErrors()) { $e = new ServerErrorHttpException('Failed to create the object for unknown reason.'); $collection->exception($e); continue; } $collection->inserted($model); } return $collection; }
/** * Updates an existing model or create new if it is not existing */ public function run() { $collection = new MultistatusCollection(); foreach ($this->items as $one) { // try to find an existing model, or create new $model = $this->tryFindModel($one) ?: $this->prepareModel(); if ($this->preProcessingModel !== null) { call_user_func($this->preProcessingModel, $model, $this); } try { if ($this->checkAccess) { call_user_func($this->checkAccess, $this->id, $model); } $isNewRecord = $model->isNewRecord; $model->load($one, ''); if ($model->save() === false && !$model->hasErrors()) { throw new ServerErrorHttpException('Failed to update the object for unknown reason.'); } $collection->{$isNewRecord ? 'inserted' : 'updated'}($model); } catch (HttpException $e) { $collection->exception($e); } } return $collection; }