hyperf-chat/app/Helper/HashIdsHelper.php

76 lines
1.4 KiB
PHP
Raw Normal View History

2020-12-01 13:54:40 +08:00
<?php
2021-09-11 12:41:28 +08:00
declare(strict_types=1);
2020-12-01 13:54:40 +08:00
2022-01-22 20:08:19 +08:00
namespace App\Helper;
2020-12-01 13:54:40 +08:00
use Hashids\Hashids;
/**
* ID加密辅助类
*
* @package App\Helper
*/
class HashIdsHelper
{
/**
* 长度
*
* @var int
*/
public static $length = 10;
/**
* 为安全起见需要修改为自己的秘钥
*
* @var string
*/
public static $secretKey = 'AqBU9zgA8EfGwVv3ghSj16n4vKS9gMtTbu';
/**
* @var Hashids
*/
protected static $hashIds;
/**
* 加密
*
* @param mixed ...$numbers
* @return string
*/
2021-09-04 18:07:53 +08:00
public static function encode(...$numbers): string
2020-12-01 13:54:40 +08:00
{
return self::getHashIds()->encode(...$numbers);
}
/**
* 解密
*
* @param string $hash
* @return array|mixed
* @throws \Exception
*/
public static function decode(string $hash)
{
$data = self::getHashIds()->decode($hash);
if (empty($data) || !is_array($data)) {
throw new \Exception('解密失败');
}
return count($data) == 1 ? $data[0] : $data;
}
/**
* 获取 HashIds 实例
*
* @return Hashids
*/
2021-09-04 18:07:53 +08:00
private static function getHashIds(): Hashids
2020-12-01 13:54:40 +08:00
{
if (!self::$hashIds instanceof Hashids) {
self::$hashIds = new Hashids(self::$secretKey, self::$length);
}
return self::$hashIds;
}
}