Ejemplo n.º 1
0
 /**
  * Импорт содержимого CSV файла
  * @param CsvModel $model
  * @return bool|array
  */
 public function import(CsvModel $model)
 {
     if (!$model->validate()) {
         return false;
     }
     if (($handle = $model->openFile()) !== false) {
         $errors = 0;
         $ok = 0;
         $i = 0;
         while (($data = $model->readLine($handle)) !== false) {
             $i++;
             if ($i == 1 and $model->headLine) {
                 continue;
             }
             $cls = $model->modelClass;
             $key = $model->key;
             if (isset($model->mapping[$key]) and !empty($data[$model->mapping[$key]])) {
                 $importModel = $cls::findOne([$key => $data[$model->mapping[$key]]]);
             }
             if (empty($importModel)) {
                 $importModel = $this->createImportModel($cls, ["scenario" => ActiveRecord::SCENARIO_INSERT]);
             }
             foreach ($model->mapping as $attr => $index) {
                 if (!is_numeric($index)) {
                     continue;
                 }
                 if ($key == 'id' and $attr == $key) {
                     continue;
                 }
                 $val = isset($data[$index]) ? $data[$index] : null;
                 $val = $this->isJson($val) ? json_decode($val) : $val;
                 $importModel->{$attr} = $val;
             }
             if (!$model->validate and $importModel->hasAttribute('active')) {
                 $importModel->active = false;
             }
             if ($importModel->save($model->validate)) {
                 $ok++;
             } else {
                 $errors++;
             }
             unset($importModel);
         }
         $model->closeFile($handle);
         return ["ok" => $ok, "errors" => $errors];
     }
     return false;
 }
Ejemplo n.º 2
0
 /**
  * Первый шаг импорта
  * @return string|\yii\web\Response
  */
 public function actionIndex()
 {
     $model = Yii::$app->session->get($this->sessionKey);
     if (!$model) {
         $model = new CsvModel();
     }
     if (Yii::$app->request->isPost) {
         $load = $model->load(Yii::$app->request->post());
         if ($load and $model->validate()) {
             Yii::$app->session->set($this->sessionKey, $model);
             return $this->redirect(['/import/admin/csv-import/import/']);
         }
     }
     $classes = Yii::$app->getModule('import')->csvImporter->getClasses();
     return $this->render("index", ["model" => $model, "classes" => $classes]);
 }