Flow.php
2.6 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
<?php
/**
* Created by PhpStorm.
* User: zhl
* Date: 2025/7/4
* Time: 11:14
*/
namespace App\Console\Commands\Statistics;
use App\Models\Project\ProjectFlow;
use App\Services\UpyunService;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
class Flow extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'project_flow_statistics';
/**
* The console command description.
*
* @var string
*/
protected $description = '项目流量统计';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct(); // 确保调用父类构造函数
}
public function handle()
{
$this->cdnStatistics();
}
public function cdnStatistics()
{
$class = new UpyunService();
list($start_at, $end_at) = $this->getTime();
$date = date('Y-m-d', strtotime($end_at));
echo 'start_at: ' . $start_at . PHP_EOL;
echo 'end_at: ' . $end_at . PHP_EOL;
$result = $class->realTimeStatistics($start_at, $end_at);
file_put_contents(storage_path('logs/flow/' . date('YmdHis', strtotime($start_at)) . '.json'), $result);
// $result = file_get_contents(storage_path('logs/flow/' . date('YmdHis', strtotime($start_at)) . '.json'));
$result = json_decode($result, true);
$flow = [];
if (FALSE == empty($result['data']) && is_array($result['data'])) {
// 结算 所有项目 流量
foreach ($result['data'] as $item) {
if (Str::startsWith($item['key'], '/upload/p/')) {
$tmp = explode('/', $item['key']);
$flow[$tmp[3]] = FALSE == empty($flow[$tmp[3]]) ? $flow[$tmp[3]] + $item['val'] : $item['val'];
}
}
}
ksort($flow);
$total_flow = 0;
foreach ($flow as $project_id=>$val) {
ProjectFlow::flowInsert($project_id, $date, $val, $end_at);
$total_flow += $val;
}
echo 'total project: ' . count($flow) . PHP_EOL;
echo 'total flow: ' . $total_flow . PHP_EOL;
return true;
}
/**
* @return array
*/
public function getTime()
{
$last_at_log = ProjectFlow::orderBy('last_at', 'desc')->first();
$today = date('Y-m-d 00:00:00');
$start_at = $last_at_log ? $last_at_log->last_at : $today;
if (strtotime($start_at) < strtotime($today))
$start_at = $today;
$end_at = date('Y-m-d H:i:s', time() - 1);
return [$start_at, $end_at];
}
}