HashidsHelper.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace common\helpers;
  3. use Hashids\Hashids;
  4. use yii\web\UnprocessableEntityHttpException;
  5. /**
  6. * ID加密辅助类
  7. *
  8. * Class HashidsHelper
  9. * @package common\helpers
  10. * @author jianyan74 <751393839@qq.com>
  11. */
  12. class HashidsHelper
  13. {
  14. /**
  15. * 长度
  16. *
  17. * @var int
  18. */
  19. public static $lenght = 6;
  20. /**
  21. * 为安全起见需要修改为自己的秘钥
  22. *
  23. * @var string
  24. */
  25. public static $secretKey = 'ZKYmp1sgcjh5KENt96bd2eSdfXSoMLPBicQCQjrW5Ee';
  26. /**
  27. * @var Hashids
  28. */
  29. protected static $hashids;
  30. /**
  31. * 加密
  32. *
  33. * @param mixed ...$numbers
  34. * @return string
  35. */
  36. public static function encode(...$numbers)
  37. {
  38. return self::getHashids()->encode(...$numbers);
  39. }
  40. /**
  41. * 解密
  42. *
  43. * @param string $hash
  44. * @return array
  45. * @throws UnprocessableEntityHttpException
  46. */
  47. public static function decode(string $hash)
  48. {
  49. $data = self::getHashids()->decode($hash);
  50. if (empty($data) || !is_array($data)) {
  51. throw new UnprocessableEntityHttpException('解密失败');
  52. }
  53. return count($data) == 1 ? $data[0] : $data;
  54. }
  55. /**
  56. * @return Hashids
  57. */
  58. private static function getHashids()
  59. {
  60. if (!self::$hashids instanceof Hashids) {
  61. self::$hashids = new Hashids(self::$secretKey, self::$lenght); // all lowercase
  62. }
  63. return self::$hashids;
  64. }
  65. }
粤ICP备19079148号