Files
hyperf_service/app/Cache/Redis/Api/EvaluationCache.php
2025-04-09 09:40:05 +08:00

57 lines
1.4 KiB
PHP

<?php
namespace App\Cache\Redis\Api;
use App\Cache\Redis\RedisCache;
use Hyperf\Di\Annotation\Inject;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
class EvaluationCache
{
/**
* @var RedisCache
*/
#[Inject]
protected RedisCache $redis;
/**
* @param int $chefId
* @param int $score
* @return void
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function addChefEvaluation(int $chefId,int $score): void
{
$key = ApiRedisKey::chefEvaluationKey($chefId);
$this->redis->hIncrBy($key, 'total_score', $score);
$this->redis->hIncrBy($key, 'total_count', 1);
}
/**
* @param int $chefId
* @return float|int
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function getChefEvaluation(int $chefId): float|int
{
$key = ApiRedisKey::chefEvaluationKey($chefId);
$totalScore = $this->redis->hGet($key, 'total_score');
$totalCount = $this->redis->hGet($key, 'total_count');
if (empty($totalScore) || empty($totalCount)) return 0;
$avgScore = $totalScore / $totalCount;
if ($avgScore < 4) {
$normalized = $avgScore / 4;
$avgScore = 4 + 1 - exp(-2 * $normalized);
}
return round($avgScore,1);
}
}