GoogleSearchKeyword.php
3.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<?php
/**
* @remark :
* @name :GoogleSearchKeyword.php
* @author :lyh
* @method :post
* @time :2025/3/31 11:29
*/
namespace App\Console\Commands\GoogleSearch;
use App\Models\Com\NoticeLog;
use App\Models\GoogleSearch\GoogleSearch;
use App\Models\GoogleSearch\GoogleSearchDetail;
use App\Models\Project\Project;
use App\Services\GoogleSearchService;
use App\Services\ProjectServer;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
/**
* @remark :客户搜索词
* @name :GoogleSearchKeyword
* @author :lyh
* @method :post
* @time :2025/3/31 11:29
*/
class GoogleSearchKeyword extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'search_keyword';
/**
* The console command description.
*
* @var string
*/
protected $description = 'google搜索词';
/**
* @remark :拉取google搜索数据
* @name :handle
* @author :lyh
* @method :post
* @time :2025/3/31 11:37
*/
public function handle(){
while (true){
$list = NoticeLog::where('type', NoticeLog::GOOGLE_SEARCH)->where('status', NoticeLog::STATUS_PENDING)->get();
if(empty($list)){
sleep(50);
return true;
}
foreach ($list as $val){
$data = json_decode($val['data'],true);
echo '执行的任务id:'.$val['id'].',项目id:'.$data['project_id']??''.PHP_EOL;
$this->_action($data['domain'],$data['type'],$data['project_id']);
echo '任务结束'.PHP_EOL;
}
}
return true;
}
/**
* @remark :执行的方法
* @name :_action
* @author :lyh
* @method :post
* @time :2025/3/31 11:30
*/
public function _action($domain,$type,$project_id){
$googleService = new GoogleSearchService();
$data = $googleService->googleSearch($domain,$type);
if(empty($data)){
echo '域名:'.$domain.'拉取数据为空.'.PHP_EOL;
return true;
}
//保存一条主记录诗句
$searchModel = new GoogleSearch();
$searchModel->addReturnId(['date'=>date('Y-m-d'),'project_id'=>$project_id,'type'=>$type,'text'=>json_encode($data,true)]);
$saveData = [];
$clicksNum = array_sum(array_column($data, 'clicks'));
$impressionsNum = array_sum(array_column($data, 'impressions'));
foreach ($data as $val){
$saveData[] = [
'date'=>date('Y-m-d'),
'project_id'=>$project_id,
'type'=>$type,
'keys'=>$val['keys'][0],
'clicks'=>$val['clicks'],
'impressions'=>$val['impressions'],
'ctr'=>$val['ctr'],
'position'=>$val['position'],
'rate'=>number_format($val['clicks'] / $clicksNum, 2),
];
}
if(!empty($saveData)){
DB::beginTransaction();
try {
//清空以前的数据
$detailModel = new GoogleSearchDetail();
$detailModel->del(['project_id'=>$project_id,'type'=>$type]);
$detailModel->insertAll($saveData);
DB::commit();
}catch (\Exception $e){
DB::rollBack();
echo '重新添加数据失败:project_id'.$project_id.PHP_EOL;
}
}
return true;
}
}