Completed
Pull Request — master (#18)
by
unknown
04:18
created

_handleGuzzleException()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 8
nc 2
nop 1
1
<?php
2
3
namespace TraderInteractive\NetAcuity\Databases;
4
5
use DominionEnterprises\Util\Arrays;
6
use Exception;
7
use GuzzleHttp\Client;
8
use GuzzleHttp\ClientInterface;
9
use GuzzleHttp\Exception\ClientException;
10
use GuzzleHttp\Psr7\Request;
11
12
/**
13
 * The Abstract NetAcuityDatabase used as a base for each database model.
14
 */
15
abstract class AbstractNetAcuityDatabase implements NetAcuityDatabaseInterface
16
{
17
    /**
18
     * @var Client The GuzzleHttp Client.
19
     */
20
    protected $client;
21
22
    /**
23
     * @var array The translations array for the data set.
24
     */
25
    protected $translations;
26
27
    /**
28
     * @var string The API User Token.
29
     */
30
    protected $apiUserToken;
31
32
    /**
33
     * @var int The Net Acuity Database ID.
34
     */
35
    protected $databaseIdentifier;
36
37
    /**
38
     * AbstractNetAcuityDatabase constructor.
39
     *
40
     * @param ClientInterface $client       The injected GuzzleHttp Client.
41
     * @param string          $apiUserToken The Net Acuity API User Token.
42
     */
43
    public function __construct(
44
        ClientInterface $client,
45
        string $apiUserToken
46
    ) {
47
        $this->client = $client;
0 ignored issues
show
Documentation Bug introduced by
$client is of type object<GuzzleHttp\ClientInterface>, but the property $client was declared to be of type object<GuzzleHttp\Client>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
48
        $this->apiUserToken = $apiUserToken;
49
    }
50
51
    /**
52
     * @param string $ip The IP to fetch the result data set for.
53
     *
54
     * @return array The formatted data set.
55
     *
56
     * @throws Exception On failure to send a Guzzle request.
57
     */
58
    public function fetch(string $ip)
59
    {
60
        $queryString = $this->buildQuery($this->apiUserToken, $ip);
61
        $request = new Request('GET', $queryString);
62
63
        $body = [];
64
        try {
65
            $response = $this->client->send($request);
66
            $body = json_decode($response->getBody()->getContents(), true);
67
        } catch (ClientException $e) {
68
            $this->handleGuzzleException($e);
69
        }
70
71
        return $this->parseBody($body);
72
    }
73
74
    /**
75
     * @param ClientException $e The thrown exception for handling.
76
     *
77
     * @throws Exception A formatted exception masking the API User Token in the event that it becomes invalid.
78
     *
79
     * @return void
80
     */
81
    protected function handleGuzzleException(ClientException $e)
82
    {
83
        $response = $e->getResponse();
84
        $code = $response->getStatusCode();
85
86
        if ($code === 403) {
87
            throw new Exception('NetAcuity API rejected the provided api user token.', $code);
88
        }
89
90
        $error = json_decode($response->getBody()->getContents(), true);
91
        $reason = Arrays::getNested($error, 'error.message');
92
93
        throw new Exception("NetAcuity API rejected the request, Reason: {$reason}", $code);
94
    }
95
96
    /**
97
     * Parses the response into an array using the field definition.
98
     *
99
     * @param array $response The response from NetAcuity.
100
     *
101
     * @return array The response where the keys are from $fields and the values are from the $response.
102
     */
103
    protected function parseBody(array $response)
104
    {
105
        $responseData = Arrays::get($response, 'response');
106
107
        $result = [];
108
        Arrays::copyIfKeysExist($responseData, $result, $this->translations);
109
110
        return $result;
111
    }
112
113
    /**
114
     * @param string $userToken Net Acuity API User Token.
115
     * @param string $ip        The IP to be referenced in the lookup.
116
     *
117
     * @return string The formatted url query string.
118
     */
119
    protected function buildQuery(string $userToken, string $ip) : string
120
    {
121
        $baseUrl = 'https://usa.cloud.netacuity.com/webservice/query';
122
        return "{$baseUrl}?u={$userToken}&dbs={$this->databaseIdentifier}&ip={$ip}&json=true";
123
    }
124
}
125