Files
hyperf_service/app/Extend/SystemUtil.php
2024-11-21 14:44:29 +08:00

95 lines
2.4 KiB
PHP

<?php
namespace App\Extend;
use Hyperf\Context\Context;
use Psr\Http\Message\ServerRequestInterface;
use function Hyperf\Support\env;
class SystemUtil
{
/**
* prod 1=生产环境 0=开发环境
* @return bool
*/
static function checkProEnv()
{
return Env('APP_ENV') == 'prod';
}
/**
* 获取客户端 ip
* @return mixed|string
*/
static function getClientIp()
{
$request = Context::get(ServerRequestInterface::class);
$ip_addr = $request->getHeaderLine('x-forwarded-for');
if (self::verifyIp($ip_addr)) {
return $ip_addr;
}
$ip_addr = $request->getHeaderLine('remote-host');
if (self::verifyIp($ip_addr)) {
return $ip_addr;
}
$ip_addr = $request->getHeaderLine('x-real-ip');
if (self::verifyIp($ip_addr)) {
return $ip_addr;
}
$ip_addr = $request->getServerParams()['remote_addr'] ?? '0.0.0.0';
if (self::verifyIp($ip_addr)) {
return $ip_addr;
}
return '0.0.0.0';
}
/**
* 验证ip
* @param $realIp
* @return mixed
*/
static function verifyIp($realIp): mixed
{
return filter_var($realIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
}
/**
* 计算距离
* @param array $locationOneArr
* @param array $locationTwoArr
* @param int $unit
* @return float|int
*/
static function calculateDistance(array $locationOneArr, array $locationTwoArr, int $unit = 1): float|int
{
// 地球平均半径,单位:公里
$earthRadius = 6371;
// 提取经纬度
$lat1 = deg2rad($locationOneArr['lat']);
$lon1 = deg2rad($locationOneArr['lng']);
$lat2 = deg2rad($locationTwoArr['lat']);
$lon2 = deg2rad($locationTwoArr['lng']);
// 计算距离
$dLat = $lat2 - $lat1;
$dLon = $lon2 - $lon1;
$a = sin($dLat / 2) * sin($dLat / 2) + cos($lat1) * cos($lat2) * sin($dLon / 2) * sin($dLon / 2);
$c = 2 * atan2(sqrt($a), sqrt(1 - $a));
// 根据单位转换距离
$distance = $earthRadius * $c;
return match ($unit) {
1 => $distance, //公里
2 => $distance * 1000, //英尺
3 => $distance * 3280.84, //米
default => 0,
};
}
}