AssociadoImport.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace App\Imports;
  3. use Carbon\Carbon;
  4. use Illuminate\Support\Collection;
  5. use Illuminate\Support\Facades\Log;
  6. use Maatwebsite\Excel\Concerns\ToCollection;
  7. use Maatwebsite\Excel\Concerns\WithCalculatedFormulas;
  8. use PhpOffice\PhpSpreadsheet\Shared\Date;
  9. use Throwable;
  10. class AssociadoImport implements ToCollection, WithCalculatedFormulas
  11. {
  12. public Collection $rows;
  13. public function collection(Collection $rows): void
  14. {
  15. $this->rows = $rows->skip(1)->values()->filter(function ($row) {
  16. return !empty(trim((string) ($row[0] ?? '')))
  17. && !empty(trim((string) ($row[1] ?? '')))
  18. && !empty(trim((string) ($row[2] ?? '')));
  19. })->map(function ($row) {
  20. $registration = trim((string) $row[0]);
  21. return [
  22. 'registration' => $registration,
  23. 'name' => trim((string) $row[1]),
  24. 'admission_date' => $this->resolveAdmissionDate($row[2] ?? null, $registration),
  25. ];
  26. })->values();
  27. }
  28. private function resolveAdmissionDate($rawValue, string $registration): ?string
  29. {
  30. try {
  31. if (is_int($rawValue) || is_float($rawValue)) {
  32. return Date::excelToDateTimeObject($rawValue)->format('Y-m-d');
  33. }
  34. if (is_string($rawValue) && is_numeric($rawValue)) {
  35. return Date::excelToDateTimeObject((float) $rawValue)->format('Y-m-d');
  36. }
  37. if (is_string($rawValue) && $rawValue !== '' && $rawValue[0] !== '=') {
  38. return Carbon::parse($rawValue)->format('Y-m-d');
  39. }
  40. } catch (Throwable $e) {
  41. // falls through to warning below
  42. }
  43. Log::warning('AssociadoImport: could not resolve admission_date, leaving null', [
  44. 'registration' => $registration,
  45. 'raw_value' => is_scalar($rawValue) ? $rawValue : json_encode($rawValue),
  46. ]);
  47. return null;
  48. }
  49. }