old-hotel-new/app/Imports/ImportBase.php

76 lines
2.1 KiB
PHP

<?php
namespace App\Imports;
use App\Exceptions\ImportException;
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
use Illuminate\Http\File;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Throwable;
class ImportBase
{
public function readFileByUrl($url)
{
$file_name = substr($url, strrpos($url, '/') + 1);
$path = DIRECTORY_SEPARATOR.'import'.DIRECTORY_SEPARATOR.date('Y-m-d').DIRECTORY_SEPARATOR.'import'.$file_name;
Storage::disk('local')->put($path, file_get_contents(str_replace(config('filesystems.disks.aliyun.domain'), config('filesystems.disks.aliyun.bucket').'.'.config('filesystems.disks.aliyun.endpoint'), $url)));
$file = new File(storage_path('app'.$path));
return $this->readFile($file);
}
public function readFile($file)
{
$reader = ReaderEntityFactory::createXLSXReader();
$reader->open($file);
$success = 0;
$fails = 0;
$errors = [];
foreach ($reader->getSheetIterator() as $sheet) {
foreach ($sheet->getRowIterator() as $num => $row) {
if ($num === 1) {
continue;
}
try {
DB::beginTransaction();
$this->loadRow($row);
$success++;
DB::commit();
} catch (ImportException $e) {
DB::rollBack();
$fails++;
$errors[] = [
'row'=>$num,
'reason'=>$e->getMessage(),
];
} catch (Throwable $e) {
DB::rollBack();
$fails++;
$errors[] = [
'row'=>$num,
'reason'=>$e->getMessage(),
];
}
}
break;
}
$reader->close();
return [
'success'=>$success,
'fails'=>$fails,
'errors'=>$errors,
];
}
public function loadRow($row)
{
return;
}
}