| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- <?php
- namespace App\Services;
- use App\Models\Import;
- use App\Models\Product;
- use Exception;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Storage;
- use Illuminate\Support\Str;
- use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
- use PhpOffice\PhpSpreadsheet\Worksheet\RowIterator;
- use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
- class ImportBaseService
- {
- protected array $headers = [];
- protected Worksheet $sheet;
- protected RowIterator $rowIterator;
- public function __construct(protected readonly Import $import)
- {}
- public function readFile(): void
- {
- $path = Storage::disk('upload')->path($this->import->filename);
- $reader = new Xlsx();
- $spreadsheet = $reader->load($path);
- $this->sheet = $spreadsheet->getActiveSheet();
- $this->rowIterator = $this->sheet->getRowIterator();
- }
- protected function rowToArray($row): array
- {
- $cellIterator = $row->getCellIterator();
- $cellIterator->setIterateOnlyExistingCells(FALSE);
- $row_content = [];
- $keys = array_values($this->headers);
- $i = 0;
- foreach ($cellIterator as $cell) {
- if (isset($keys[$i])) {
- $row_content[$keys[$i]] = $cell->getValue();
- }
- $i++;
- }
- return $row_content;
- }
- /**
- * @param array $headers
- * @return bool
- */
- protected function checkHeaders(array $headers): bool
- {
- foreach ($headers as $k => $header) {
- $headers[$k] = Str::before($header, "\n");
- }
- return $headers == array_keys($this->headers);
- }
- protected function findId(string $tableNameCol, string $value): string
- {
- list($table, $column) = explode('.', $tableNameCol);
- $model = DB::table($table)
- ->where($column, $value)
- ->first();
- if (!$model) {
- echo $this->import->log("SKIP: no {$tableNameCol} {$value} found!", 'WARNING');
- }
- return $model?->id ?? '';
- }
- protected function prepare(): bool
- {
- try {
- $this->import->log('Reading file...');
- $this->readFile();
- } catch (Exception $exception){
- $this->import->log($exception->getMessage(), 'ERROR');
- $this->import->status = 'ERROR';
- $this->import->save();
- return false;
- }
- try {
- $this->import->log('Checking headers...');
- $headers = $this->rowToArray($this->rowIterator->current());
- if (!$this->checkHeaders(array_values($headers))) {
- throw new Exception("Invalid headers");
- }
- } catch (Exception $exception){
- $this->import->log($exception->getMessage(), 'ERROR');
- $this->import->status = 'ERROR';
- $this->import->save();
- return false;
- }
- return true;
- }
- }
|