Skip to content

Instantly share code, notes, and snippets.

@chabibnr
Created August 8, 2017 03:39
Show Gist options
  • Save chabibnr/84177d1eeb6e59cb52d1766c2e84cbfd to your computer and use it in GitHub Desktop.
Save chabibnr/84177d1eeb6e59cb52d1766c2e84cbfd to your computer and use it in GitHub Desktop.
public function actionReadImportFile($id) {
$data = Yii::$app->session['import_kuesioner'];
$path = \Yii::getAlias('@webroot') . '/uploads/kuesioner/' . $data . '';
try {
$inputFileType = \PHPExcel_IOFactory::identify($path);
$objReader = \PHPExcel_IOFactory::createReader($inputFileType);
libxml_use_internal_errors(true);
$objPHPExcel = $objReader->load($path);
} catch (Exception $e) {
die('Error');
}
$objWorksheet = $objPHPExcel->getSheet(0);
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$group = [];
$current =0;
$autoNumber = 1;
$ruleError = [];
for ($row = 9; $row <= $highestRow; ++$row) {
$rowData = $objWorksheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
//Rules
$rules = $this->excelRules($rowData[0][2], $rowData[0][4], $rowData[0][9], $rowData[0][10], $rowData[0][5],$rowData[0][3], $rowData[0][14]);
//var_dump($rules);
if(is_array($rules)){
$ruleError[$row] = $rules['message'];
}
$tanggalDibuat = !empty($rowData[0][6]) ? date('Y-m-d', strtotime($rowData[0][6])) : date('Y-m-d');
$tanggalDiupdate = !empty($rowData[0][7]) ? date('Y-m-d', strtotime($rowData[0][7])) : date('Y-m-d');
if(!empty($rowData[0][0])) {
$group[$row] = [
'no' => $rowData[0][0],
'group_title' => $rowData[0][1],
'pertanyaan' => $rowData[0][2],
'list_pertanyaan_add' => $rowData[0][3],
'jenis' => $rowData[0][4],
'opsi' => $rowData[0][5],
'tanggal_dibuat' => $tanggalDibuat,
'tanggal_diupdate' => $tanggalDiupdate,
'urutan' => empty($rowData[0][8]) ? $autoNumber : $rowData[0][8],
'min' => $rowData[0][9],
'max' => $rowData[0][10],
'default' => $rowData[0][11],
'keterangan' => $rowData[0][12],
'required' => $rowData[0][13],
'score' => $rowData[0][14],
'selanjutnya' => $rowData[0][15],
'id' => !isset($rowData[0][16])?: $rowData[0][16],
'childrens' => []
];
$current = $row;
}else {
$group[$current]['childrens'][] = [
'no' => $rowData[0][0],
'pertanyaan' => $rowData[0][2],
'list_pertanyaan_add' => $rowData[0][3],
'jenis' => $rowData[0][4],
'opsi' => $rowData[0][5],
'tanggal_dibuat' => $tanggalDibuat,
'tanggal_diupdate' => $tanggalDiupdate,
'urutan' => empty($rowData[0][8]) ? $autoNumber : $rowData[0][8],
'min' => $rowData[0][9],
'max' => $rowData[0][10],
'default' => $rowData[0][11],
'keterangan' => $rowData[0][12],
'required' => $rowData[0][13],
'score' => $rowData[0][14],
'selanjutnya' => $rowData[0][15],
'id' => !isset($rowData[0][16])?: $rowData[0][16],
];
}
$autoNumber++;
}
if(count($ruleError) > 0){
$message = '';
foreach($ruleError as $baris => $pesan){
$message .= "<br/>- Baris ke {$baris} : {$pesan}";
}
Yii::$app->getSession()->setFlash('error', 'Gagal import. <br/>'. $message);
unlink($path);
return $this->redirect(['kuesioner/manage']);
}
unlink($path);
if (KuesionerPertanyaan::executeFromImport($group, $id)) {
Yii::$app->getSession()->setFlash('success', 'Berhasil update import file.');
return $this->redirect(['kuesioner/pertanyaan', 'id' => $id]);
} else {
Yii::$app->getSession()->setFlash('error', 'Gagal import. Silahkan periksa kembali data anda.');
return $this->redirect(['kuesioner/manage']);
}
// return $this->redirect(['keranjang']);
}
private function excelRules($pertanyaan, $jenis, $min, $max, $opsi, $kolom, $score){
$pertanyaan = trim(trim($pertanyaan), '-');
$jenis = trim(trim($jenis), '-');
$min = trim(trim($min), '-');
$max = trim(trim($max), '-');
$opsi = trim(trim($opsi), '-');
$kolom = trim(trim($kolom), '-');
$jenisPertanyaan = ['text','numeric','single','multiple', 'date'];
//cek jenis pertanyaan
if(!in_array($jenis, $jenisPertanyaan)){
return [
'status' => 'error',
'message' => 'Jenis pertanyaan tidak sesuai, jenis yang di ijinkan '. implode(',', $jenisPertanyaan).'. Anda memasukan '. $jenis
];
} elseif($jenis == 'numeric' || $jenis == 'date'){
if(!empty($min) || !empty($max) || !empty($opsi) || !empty($kolom)){
return [
'status' => 'error',
'message' => 'Jenis pertanyaan Numeric atau Date tidak membutuhkan Min, Max, Opsi, Kolom'
];
}
} elseif($jenis == 'single' || $jenis == 'multiple'){
if(!empty($min) || !empty($max) || !empty($kolom)){
return [
'status' => 'error',
'message' => 'Jenis pertanyaan Single atau Multiple tidak membutuhkan Min, Max, Kolom'
];
}
} elseif($jenis == 'single'){
$scores = explode(',',$score);
if(count(explode(',', $opsi)) != count($scores)){
return [
'status' => 'error',
'message' => 'Jumlah Opsi dan Score tidak sama'
];
}
foreach($scores as $skor){
if($skor < 0 || $skor > 10){
return [
'status' => 'error',
'message' => 'Nilai Score antara 0 - 10'
];
}
}
} elseif(empty($pertanyaan)){
return [
'status' => 'error',
'message' => 'Pertanyaan Harus diisi'
];
} else {
return true;
}
}
private static $noToId = [];
public static function executeFromImport($data, $kuesionerId){
static::$noToId = [];
$data = is_array($data) ? $data : [];
foreach($data as $row){
$no = $row['no'];
$modelUtama = !empty($row['id']) ? static::findOne(['id' => $row['id'], 'kuesioner' => $kuesionerId ]) : new static();
$modelUtama = $modelUtama == false ? new static() : $modelUtama;
$row['kuesioner'] = $kuesionerId;
$row['is_group'] = count($row['childrens']) > 0 ? 1 :0;
$opsiList = explode(',', $row['opsi']);
$scoreList = explode(',', $row['score']);
$pertanyaanSelanjutnya = explode(',', $row['selanjutnya']);
unset($row['no']);
unset($row['score']);
unset($row['selanjutnya']);
$modelUtama->attributes = $row;
$isCreate = $modelUtama->isNewRecord;
if($modelUtama->save(false)){
static::$noToId[$no] = $modelUtama->id;
//echo "<br/>". ($isCreate ? 'create' : 'update') ." sukses ". $modelUtama->id . ' = '.$row['pertanyaan'];
if($row['jenis'] == 'single'){
foreach($opsiList as $key => $opsi){
try {
if ($isCreate) {
$nextPertanyaan = isset($pertanyaanSelanjutnya[$key]) ? $pertanyaanSelanjutnya[$key] : NULL;
$advanceModel = new KuesionerAdvancedOption();
$advanceModel->score = isset($scoreList[$key]) ? (int)$scoreList[$key] : 0;
$advanceModel->pertanyan = $modelUtama->id;
$advanceModel->jawaban = $opsi;
$advanceModel->pertanyaan_selanjutnya = $nextPertanyaan != NULL ? (isset(static::$noToId[$nextPertanyaan]) ? static::$noToId[$nextPertanyaan] : NULL) : NULL;
} else {
$score = explode(':', $scoreList[$key]);
$advanceModel = KuesionerAdvancedOption::findOne(['id' => $score[0]]);
$advanceModel->score = $score[1];
$advanceModel->jawaban = $opsi;
$advanceModel->pertanyaan_selanjutnya = isset($pertanyaanSelanjutnya[$key]) ? $pertanyaanSelanjutnya[$key] : NULL;
}
$advanceModel->save(false);
}catch (Exception $e){
}
}
}
} else {
//print_r($modelUtama->errors);
}
foreach($row['childrens'] as $children){
$modelSub = !empty($children['id']) ? static::findOne(['id' => $children['id'], 'kuesioner' => $kuesionerId ]) : new static();
$modelSub = $modelSub == false ? new static() : $modelSub;
$children['group'] = $modelUtama->id;
$children['kuesioner'] = $kuesionerId;
$modelSub->attributes = $children;
$isCreate = $modelSub->isNewRecord;
if($modelSub->save(false)){
//echo "<br/>". ($isCreate ? 'create' : 'update') ."-- SUkses sub ". $modelSub->id . '-- '. $children['pertanyaan'];
} else {
//print_r($modelSub->errors);
}
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment