TaobaoIp::formatResult()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 11
ccs 9
cts 9
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 1
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
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.
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