/** * Импорт содержимого 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; }