DuC-cnZj /
ip
| 1 | <?php |
||
| 2 | |||
| 3 | namespace DucCnzj\Ip\Strategies; |
||
| 4 | |||
| 5 | use DucCnzj\Ip\Imp\IpImp; |
||
| 6 | use GuzzleHttp\ClientInterface; |
||
| 7 | use GuzzleHttp\Exception\ClientException; |
||
| 8 | use GuzzleHttp\Exception\ServerException; |
||
| 9 | use DucCnzj\Ip\Exceptions\ServerErrorException; |
||
| 10 | |||
| 11 | class TaobaoIp implements IpImp |
||
| 12 | { |
||
| 13 | protected $url = 'http://ip.taobao.com/service/getIpInfo.php'; |
||
| 14 | |||
| 15 | /** |
||
| 16 | * @param ClientInterface $httpClient |
||
| 17 | * |
||
| 18 | * @param string $ip |
||
| 19 | * |
||
| 20 | * @return array |
||
| 21 | * @throws ServerErrorException |
||
| 22 | * @throws \GuzzleHttp\Exception\GuzzleException |
||
| 23 | * @author duc <[email protected]> |
||
| 24 | */ |
||
| 25 | 5 | public function send(ClientInterface $httpClient, string $ip):array |
|
| 26 | { |
||
| 27 | try { |
||
| 28 | 5 | $originalStr = $httpClient->request('get', $this->url . '?ip=' . $ip) |
|
| 29 | 3 | ->getBody(); |
|
| 30 | |||
| 31 | 3 | $result = json_decode($originalStr, true); |
|
| 32 | |||
| 33 | 3 | if ($result['code'] !== 0) { |
|
| 34 | 1 | throw new ServerErrorException(); |
|
| 35 | } |
||
| 36 | |||
| 37 | 2 | $data['ip'] = $ip; |
|
|
0 ignored issues
–
show
Comprehensibility
Best Practice
introduced
by
Loading history...
|
|||
| 38 | |||
| 39 | 2 | $data = $this->formatResult($data, $result); |
|
| 40 | |||
| 41 | 2 | return $data; |
|
| 42 | 3 | } catch (ServerException $e) { |
|
| 43 | 1 | throw new ServerErrorException(); |
|
| 44 | 2 | } catch (ClientException $e) { |
|
| 45 | 1 | throw new ServerErrorException(); |
|
| 46 | } |
||
| 47 | } |
||
| 48 | |||
| 49 | /** |
||
| 50 | * @param array $result |
||
| 51 | * @param array $data |
||
| 52 | * |
||
| 53 | * @return array |
||
| 54 | * |
||
| 55 | * @author duc <[email protected]> |
||
| 56 | */ |
||
| 57 | 2 | public function formatResult(array $data, array $result) |
|
| 58 | { |
||
| 59 | 2 | $data['country'] = $result['data']['country']; |
|
| 60 | 2 | $data['region'] = $result['data']['region']; |
|
| 61 | 2 | $data['city'] = $result['data']['city']; |
|
| 62 | 2 | $data['address'] = $data['country'] . $data['region'] . $data['city']; |
|
| 63 | 2 | $data['point_x'] = ''; |
|
| 64 | 2 | $data['point_y'] = ''; |
|
| 65 | 2 | $data['isp'] = $result['data']['isp']; |
|
| 66 | |||
| 67 | 2 | return $data; |
|
| 68 | } |
||
| 69 | } |
||
| 70 |