ImportBaseService.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace App\Services;
  3. use App\Models\Import;
  4. use App\Models\Product;
  5. use Illuminate\Support\Facades\DB;
  6. use Illuminate\Support\Facades\Storage;
  7. use Illuminate\Support\Str;
  8. use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
  9. use PhpOffice\PhpSpreadsheet\Worksheet\RowIterator;
  10. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  11. class ImportBaseService
  12. {
  13. protected array $headers = [];
  14. protected Worksheet $sheet;
  15. protected RowIterator $rowIterator;
  16. public function __construct(protected readonly Import $import)
  17. {}
  18. public function readFile(): void
  19. {
  20. $path = Storage::disk('upload')->path($this->import->filename);
  21. $reader = new Xlsx();
  22. $spreadsheet = $reader->load($path);
  23. $this->sheet = $spreadsheet->getActiveSheet();
  24. $this->rowIterator = $this->sheet->getRowIterator();
  25. }
  26. protected function rowToArray($row): array
  27. {
  28. $cellIterator = $row->getCellIterator();
  29. $cellIterator->setIterateOnlyExistingCells(FALSE);
  30. $row_content = [];
  31. $keys = array_values($this->headers);
  32. $i = 0;
  33. foreach ($cellIterator as $cell) {
  34. $row_content[$keys[$i++]] = $cell->getValue();
  35. }
  36. return $row_content;
  37. }
  38. /**
  39. * @param array $headers
  40. * @return bool
  41. */
  42. protected function checkHeaders(array $headers): bool
  43. {
  44. foreach ($headers as $k => $header) {
  45. $headers[$k] = Str::before($header, "\n");
  46. }
  47. return $headers == array_keys($this->headers);
  48. }
  49. protected function findId(string $tableNameCol, string $value): string
  50. {
  51. list($table, $column) = explode('.', $tableNameCol);
  52. $model = DB::table($table)
  53. ->where($column, $value)
  54. ->first();
  55. if (!$model) {
  56. echo $this->import->log("SKIP: no {$tableNameCol} {$value} found!", 'WARNING');
  57. }
  58. return $model?->id ?? '';
  59. }
  60. }