Driver.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace App\Utils\Encrypt\Token;
  3. use Hyperf\Config\Annotation\Value;
  4. /**
  5. * Token基础类
  6. */
  7. abstract class Driver
  8. {
  9. protected $handler = null;
  10. protected array $options = [];
  11. #[Value("token.default")]
  12. protected array $config = [];
  13. /**
  14. * 存储Token
  15. * @param string $token Token
  16. * @param int $user_id 会员ID
  17. * @param int $expire 过期时长,0表示无限,单位秒
  18. * @return bool
  19. */
  20. abstract function set(string $token, int $user_id, int $expire = 0);
  21. /**
  22. * 获取Token内的信息
  23. * @param string $token
  24. * @return array
  25. */
  26. abstract function get(string $token);
  27. /**
  28. * 判断Token是否可用
  29. * @param string $token Token
  30. * @param int $user_id 会员ID
  31. * @return boolean
  32. */
  33. abstract function check(string $token, int $user_id): bool;
  34. /**
  35. * 删除Token
  36. * @param string $token
  37. * @return boolean
  38. */
  39. abstract function delete(string $token): bool;
  40. /**
  41. * 删除指定用户的所有Token
  42. * @param int $user_id
  43. * @return boolean
  44. */
  45. abstract function clear(int $user_id): bool;
  46. /**
  47. * 返回句柄对象,可执行其它高级方法
  48. *
  49. * @access public
  50. * @return object
  51. */
  52. public function handler()
  53. {
  54. return $this->handler;
  55. }
  56. /**
  57. * 获取加密后的Token
  58. * @param string $token Token标识
  59. * @return string
  60. */
  61. protected function getEncryptedToken(string $token): string
  62. {
  63. return hash_hmac($this->config['hash_algo'], $token, $this->config['key']);
  64. }
  65. /**
  66. * 获取过期剩余时长
  67. * @param $expiretime
  68. * @return float|int|mixed
  69. */
  70. protected function getExpiredIn($expire_time)
  71. {
  72. return $expire_time ? max(0, $expire_time - time()) : 365 * 86400;
  73. }
  74. }