新增比较APP版本号方法

This commit is contained in:
2026-08-05 17:30:01 +08:00
parent d371031dac
commit b90552553b

View File

@@ -10,6 +10,7 @@ namespace Dhd\Micro\Core\Trait;
use Hyperf\Rpc\Context as RpcContext;
use Dhd\Micro\Core\Library\Util;
use Hyperf\Collection\Arr;
trait RpcContextTrait
{
@@ -36,4 +37,38 @@ trait RpcContextTrait
{
return Util::get(RpcContext::class)->get('platform_name');
}
/**
* 与APP当前版本比较版本号大小,APP版本在方法中自动获取
* @param string $version 要比较的版本号
* @return int ---------------------------------------------------返回 -1、0 或 1,分别表示 请求的版本 小于、等于或大于 $version
*/
public function compareVersion(string $version): int
{
$appVersion = $this->getAppVersion();
if (empty($appVersion)) {
return -1;
}
$v1Parts = explode('.', $appVersion);
$v2Parts = explode('.', $version);
// 获取最大长度以进行逐位比较
$maxLength = max(count($v1Parts), count($v2Parts));
for ($i = 0; $i < $maxLength; $i++) {
$num1 = intval(Arr::get($v1Parts, $i, 0));
$num2 = intval(Arr::get($v2Parts, $i, 0));
if ($num1 < $num2) {
return -1;
} elseif ($num1 > $num2) {
return 1;
}
// 如果相等,继续比较下一位
}
// 所有部分都相等
return 0;
}
}