DemoImport.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. namespace App\Imports;
  3. use App\Http\Logics\Admin\SiteSyncLogic;
  4. use App\Http\Models\Server;
  5. use App\Http\Models\Site;
  6. use Illuminate\Support\Collection;
  7. use Illuminate\Support\Facades\DB;
  8. use Illuminate\Support\Facades\Log;
  9. use Illuminate\Validation\Rule;
  10. use Maatwebsite\Excel\Concerns\Importable;
  11. use Maatwebsite\Excel\Concerns\ToCollection;
  12. use Maatwebsite\Excel\Concerns\WithMappedCells;
  13. use Maatwebsite\Excel\Concerns\WithValidation;
  14. class DemoImport implements ToCollection
  15. {
  16. use Importable;
  17. public function __construct()
  18. {
  19. }
  20. const FIELD_MAP = [
  21. 2 => 'domain',
  22. 3 => 'server_ip',
  23. 4 => 'api_url',
  24. 5 => 'webmaster_domain',
  25. 6 => 'report_day'
  26. ];
  27. public function collection(Collection $collections)
  28. {
  29. //
  30. $allSites = Site::query()->get();
  31. //
  32. $serverMap = Server::all()->pluck('server_id', 'server_ip')->toArray();
  33. $all = collect([]);
  34. foreach ($collections as $key => $collection) {
  35. if ($key < 1 || empty($collection[0]) || empty($collection[2])) {
  36. continue;
  37. }
  38. $temp = $this->fieldMap($collection);
  39. $all->push($temp);
  40. }
  41. $items = $all->toArray();
  42. $siteSync = new SiteSyncLogic();
  43. foreach ($items as $key => $item) {
  44. $temp = $allSites->where('domain', $item['domain'])->first();
  45. if ($temp) {
  46. $updated = [
  47. 'server_id' => $serverMap[$item['server_ip']] ?? 0,
  48. 'api_url' => $item['api_url'],
  49. 'webmaster_domain' => $item['webmaster_domain'],
  50. 'report_day' => $item['report_day']
  51. ];
  52. $temp->update($updated);
  53. $syncUpdate = $temp->toArray() + ['server_ip' => $item['server_ip']];
  54. $siteSync->update($temp->old_id, $siteSync->fieldMap($syncUpdate));
  55. } else {
  56. echo $item['domain'] . '<br>';
  57. }
  58. }
  59. dump('success');
  60. }
  61. public function fieldMap($collect): array
  62. {
  63. $result = [];
  64. foreach ($collect as $inx => $val) {
  65. if (empty(self::FIELD_MAP[$inx])) continue;
  66. if (self::FIELD_MAP[$inx] == 'report_day') {
  67. $result[self::FIELD_MAP[$inx]] = intval($val);
  68. } else {
  69. $result[self::FIELD_MAP[$inx]] = $val;
  70. }
  71. }
  72. return $result;
  73. }
  74. }