Keyword.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace App\Imports;
  3. use Illuminate\Support\Collection;
  4. use Illuminate\Support\Facades\DB;
  5. use Illuminate\Support\Facades\Log;
  6. use Illuminate\Validation\Rule;
  7. use Maatwebsite\Excel\Concerns\Importable;
  8. use Maatwebsite\Excel\Concerns\ToCollection;
  9. use Maatwebsite\Excel\Concerns\WithMappedCells;
  10. use Maatwebsite\Excel\Concerns\WithValidation;
  11. class Keyword implements ToCollection
  12. {
  13. use Importable;
  14. protected $projectId;
  15. public function __construct($projectId)
  16. {
  17. $this->projectId = $projectId;
  18. }
  19. // const FIELD_MAP = [
  20. // 0 => 'sn',
  21. // 1 => 'level',
  22. // 2 => 'keyword',
  23. // 3 => 'chinese_keyword',
  24. // 4 => 'page_title',
  25. // 5 => 'page_url',
  26. // 6 => 'search_num',
  27. // ];
  28. const FIELD_MAP = [
  29. 0 => 'keyword',
  30. 1 => 'chinese_keyword',
  31. 2 => 'page_url',
  32. 3 => 'search_num',
  33. ];
  34. public function collection(Collection $collections)
  35. {
  36. $all = collect([]);
  37. $rankConnection = DB::connection('rank');
  38. $maxSn = $rankConnection->table('project_keyword')->where(['project_id' => $this->projectId])->max('sn') ?? 0;
  39. foreach ($collections as $key => $collection) {
  40. if ($key < 1) {
  41. continue;
  42. }
  43. $temp = $this->fieldMap($collection);
  44. if (mb_strlen($temp['keyword']) < 1) {
  45. continue;
  46. }
  47. $maxSn++;
  48. $all->push(($temp + ['sn' => $maxSn]));
  49. }
  50. $allItems = $all->chunk(2500)->toArray();
  51. foreach ($allItems as $item) {
  52. $rankConnection->table('project_keyword')->insert($item);
  53. }
  54. }
  55. public function fieldMap($collect): array
  56. {
  57. $result = [
  58. 'google_rank' => 9999,
  59. 'allintitle' => -1,
  60. 'sync_time' => strtotime('+1 day'),
  61. 'project_id' => $this->projectId
  62. ];
  63. foreach ($collect as $inx => $val) {
  64. if (empty(self::FIELD_MAP[$inx])) continue;
  65. if (in_array(self::FIELD_MAP[$inx], ['sn', 'search_num'])) {
  66. $result[self::FIELD_MAP[$inx]] = intval($val);
  67. } else {
  68. $result[self::FIELD_MAP[$inx]] = $val;
  69. }
  70. }
  71. return $result;
  72. }
  73. }