Files
fn_b/app/Console/Commands/SyncArticleLikes.php
T

89 lines
3.6 KiB
PHP
Executable File

<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\Articles;
use Illuminate\Support\Facades\Cache;
use App\Services\CacheService;
use App\Services\OneYearArticleLikes;
class SyncArticleLikes extends Command
{
// 在 Kernel.php 中建议设置 ->everyFiveMinutes()
protected $signature = 'article:sync-likes';
protected $description = '文章点赞:短期额度、持续年度随机增长、一次性年度额度';
public function handle(OneYearArticleLikes $oneYearLikes)
{
$iBurstCount = 0; // 记录本次执行爆发了多少文章
$iYearlyCount = 0; // 记录本次执行有多少文章中了全年奖
// 1. 【7天爆发】碎化注入逻辑
Articles::where('i7like', '>', 0)
->where('iStatus', 1)
->chunkById(100, function ($aArticles) use (&$iBurstCount) {
foreach ($aArticles as $oArticle) {
$iDaysPassed = $oArticle->created_at->diffInDays(now());
if ($iDaysPassed > 6) continue;
$iRemainingSlots = (7 - $iDaysPassed) * 24 * 12;
if ($iRemainingSlots <= 0) continue;
$iBaseAdd = (int)ceil($oArticle->i7like / $iRemainingSlots);
if (mt_rand(1, 100) <= 50) {
$iAdd = mt_rand(1, max(1, $iBaseAdd * 2));
$this->transferLikes($oArticle, 'i7like', $iAdd);
$this->info("ID [{$oArticle->id}] 爆发:注入 {$iAdd} 个赞,剩余库存 {$oArticle->i7like}");
$iBurstCount++;
}
}
});
// 2. 【全年增长】天级随机逻辑
$sLockKey = 'sync_yearly_likes_lock:' . now()->format('Ymd');
if (!Cache::has($sLockKey)) {
$this->warn("检测到今日尚未进行全年随机摇号,开始抽奖...");
Articles::where('i365like', '>', 0)
->where('iStatus', 1)
->chunkById(100, function ($aArticles) use (&$iYearlyCount) {
foreach ($aArticles as $oArticle) {
if (mt_rand(1, 365) <= $oArticle->i365like) {
$oArticle->increment('iLikeCount');
$this->line("ID [{$oArticle->id}] 全年:运气爆发,喜提 1 个赞");
$iYearlyCount++;
}
}
});
Cache::put($sLockKey, 1, now()->addDay());
}
$oneYearAdded = $oneYearLikes->sync();
CacheService::updateOrderLikes();
$this->comment("本次任务结束:{$iBurstCount} 篇爆发增长,{$iYearlyCount} 篇全年喜提。");
$this->comment("一次性年度额度本次增加 {$oneYearAdded} 赞,额度用完后停止。");
}
/**
* 核心转移逻辑
*/
private function transferLikes(Articles $oArticle, string $sField, int $iAmount): void
{
$iRealAdd = min($oArticle->$sField, $iAmount);
if ($iRealAdd > 0) {
$oArticle->increment('iLikeCount', $iRealAdd, [
'sLastLikedAt' => now(), // 这里的 now() 是 Laravel 提供的 Carbon 实例
]);
// 这里注意:increment/decrement 会同步更新 model 对象的内存值
$oArticle->decrement($sField, $iRealAdd);
// $oArticle->sLastLikedAt = time();
// $oArticle->save();
}
}
}