ToolService.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /*
  3. * 工具服务
  4. */
  5. namespace App\Services;
  6. class ToolService
  7. {
  8. // 静态对象
  9. protected static $instance = null;
  10. protected $apiUrls = [
  11. // ip编号信息
  12. 'ip-api'=>'http://ip-api.com/json/%s?lang=%s',
  13. // IP解析
  14. 'ip-api—data'=>'https://www.ip.cn/api/index?ip=%s&type=1',
  15. ];
  16. /**
  17. * @return static|null
  18. */
  19. public static function make(){
  20. if(!self::$instance){
  21. self::$instance = new static();
  22. }
  23. return self::$instance;
  24. }
  25. /**
  26. * 获取IP对应地址
  27. * @param $ip IP
  28. * @param $returnKey 返回数据格式:返回某个字段,空返回全部
  29. * @param $lang 返回数据语言格式:zh-CN(中文)、en(英文拼音)
  30. * @return array|bool
  31. */
  32. public function getIpAddress($ip, $returnKey = '', $lang='zh-CN'){
  33. $apiUrl = $this->apiUrls['ip-api'];
  34. if(empty($urls) || empty($ip)){
  35. return false;
  36. }
  37. $cacheKey = "caches:address:ip_".$ip.'_'.$returnKey;
  38. $result = RedisService::get($cacheKey);
  39. $data = isset($result['data']) && !is_array($result['data'])? trim($result['data']) : '';
  40. if(!empty($data)){
  41. return $data;
  42. }
  43. $apiUrl = sprintf($apiUrl, $ip, $lang);
  44. $result = httpRequest($apiUrl,'','get');
  45. $status = isset($result['status'])? $result['status'] : '';
  46. if($status == 'success'){
  47. $result = [
  48. 'country'=> isset($result['country'])? strtolower($result['country']) : '中国',
  49. 'countryCode'=> isset($result['countryCode'])? strtolower($result['countryCode']) : 'zh-CN',
  50. 'region'=> isset($result['region'])? $result['region'] : '',
  51. 'regionName'=> isset($result['regionName'])? $result['regionName'] : '',
  52. 'city'=> isset($result['city'])? $result['city'] : '',
  53. 'lat'=> isset($result['lat'])? $result['lat'] : '',
  54. 'lng'=> isset($result['lon'])? $result['lon'] : '',
  55. 'ip'=> isset($result['query'])? $result['query'] : '',
  56. ];
  57. $data = $returnKey && isset($result[$returnKey])? $result[$returnKey] : $result;
  58. if(!empty($data)){
  59. RedisService::set($cacheKey, ['apiUrl'=> $apiUrl, 'data'=> $data, 'result'=> $result], 3600);
  60. return $data;
  61. }
  62. }
  63. return false;
  64. }
  65. }