Completed
Push — master ( f1fbf7...edaf05 )
by Tristan
02:41
created

RestClient::processResponse()   C

Complexity

Conditions 7
Paths 5

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 12
nc 5
nop 1
1
<?PHP
2
3
/**
4
 * MyPoseo API Bundle
5
 *
6
 * @author Tristan Bessoussa <[email protected]>
7
 */
8
9
namespace Tristanbes\MyPoseoBundle\Connection;
10
11
use Http\Client\HttpClient;
12
use Http\Client\Common\PluginClient;
13
use Psr\Cache\CacheItemPoolInterface;
14
use Psr\Http\Message\ResponseInterface;
15
use Http\Discovery\HttpClientDiscovery;
16
use Http\Discovery\MessageFactoryDiscovery;
17
use Http\Message\Authentication\QueryParam;
18
use Http\Client\Common\Plugin\AuthenticationPlugin;
19
20
use Tristanbes\MyPoseoBundle\Exception\ThrottleLimitException;
21
use Tristanbes\MyPoseoBundle\Exception\NotEnoughCreditsException;
22
23
/**
24
 * This class is a wrapper for the HTTP client.
25
 */
26
class RestClient
27
{
28
    /**
29
     * Your API key.
30
     *
31
     * @var string
32
     */
33
    private $apiKey;
34
35
    /**
36
     * @var HttpClient
37
     */
38
    protected $httpClient;
39
40
    /**
41
     * @var string
42
     */
43
    protected $apiHost;
44
45
    /**
46
     * @var CacheItemPoolInterface
47
     */
48
    protected $cache;
49
50
    /**
51
     * @param string                 $apiKey
52
     * @param string                 $apiHost
53
     * @param HttpClient             $httpClient
54
     * @param CacheItemPoolInterface $cache
55
     */
56
    public function __construct($apiKey, $apiHost, $httpClient = null, CacheItemPoolInterface $cache = null)
57
    {
58
        $this->apiKey     = $apiKey;
59
        $this->apiHost    = $apiHost;
60
        $this->httpClient = $httpClient;
61
        $this->cache      = $cache;
62
    }
63
64
     /**
65
     * @return HttpClient
66
     */
67
    protected function getHttpClient()
68
    {
69
        if ($this->httpClient === null) {
70
            $this->httpClient = HttpClientDiscovery::find();
71
        }
72
73
        $authentication = new QueryParam(['key' => $this->apiKey]);
74
75
        $authenticationPlugin = new AuthenticationPlugin($authentication);
76
77
        $client = new PluginClient($this->httpClient, [$authenticationPlugin]);
78
79
        return $client;
80
    }
81
82
    /**
83
     * Sends the API request if cache not hit
84
     *
85
     * @param string  $method
86
     * @param string  $uri
87
     * @param null    $body
88
     * @param array   $headers
89
     * @param string  $cacheKey
90
     * @param integer $ttl
91
     *
92
     * @return array
93
     */
94
    public function send($method, $uri, $body = null, array $headers = [], $cacheKey = null, $ttl = null)
95
    {
96
        $saveToCache = false;
97
98
        if ($cacheKey !== null && $ttl !== null && $this->cache) {
99
            if ($this->cache->hasItem($cacheKey)) {
100
                return $this->cache->getItem($cacheKey)->get();
101
            } else {
102
                $saveToCache = true;
103
            }
104
        }
105
106
        if (is_array($body)) {
107
            $body = http_build_query($body);
108
            $headers['Content-Type'] = 'application/x-www-form-urlencoded';
109
        }
110
111
        $request = MessageFactoryDiscovery::find()->createRequest($method, $this->getApiUrl($uri), $headers, $body);
112
        $rawResponse = $this->getHttpClient()->sendRequest($request);
113
114
        $data = $this->processResponse($rawResponse);
115
116
        if ($this->cache && true === $saveToCache) {
117
            $item = $this->cache
118
                ->getItem($cacheKey)
119
                ->set($data)
120
                ->expiresAfter($ttl)
121
            ;
122
123
            $this->cache->save($item);
124
        }
125
126
        return $data;
127
    }
128
129
    /**
130
     * Process the API response, provides error handling
131
     *
132
     * @param ResponseInterface $response
133
     *
134
     * @throws \Exception
135
     *
136
     * @return array
137
     */
138
    public function processResponse(ResponseInterface $response)
139
    {
140
        $httpResponseCode = (int) $response->getStatusCode();
0 ignored issues
show
Unused Code introduced by
$httpResponseCode is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
141
142
        $data = (string) $response->getBody();
143
        $jsonResponseData = json_decode($data, true);
144
        
145
        if (isset($jsonResponseData['status']) && $jsonResponseData['status'] != "success") {
146
            throw new \Exception('MyPoseo API: '.$data['message']);
147
        }
148
149
        if (isset($jsonResponseData['myposeo']['code'])) {
150
            if ($jsonResponseData['myposeo']['code'] == '-1' && $jsonResponseData['myposeo']['message'] == 'No enough credits') {
151
                throw new NotEnoughCreditsException();
152
            }
153
154
            if ($jsonResponseData['myposeo']['code'] == '-1') {
155
                throw new ThrottleLimitException();
156
            }
157
        }
158
159
        return $jsonResponseData;
160
    }
161
162
    /**
163
     * @param string       $endpointUrl
164
     * @param array        $queryString
165
     * @param string|null  $cacheKey
166
     * @param integer|null $ttl
167
     *
168
     * @return ResponseInterface
169
     */
170
    public function get($endpointUrl, $queryString = [], $cacheKey = null, $ttl = null)
171
    {
172
        return $this->send('GET', $endpointUrl.'?'.http_build_query($queryString), null, [], $cacheKey, $ttl);
173
    }
174
175
    /**
176
     * @param string $endpointUrl
177
     * @param array  $postData
178
     *
179
     * @return \stdClass
180
     */
181
    public function post($endpointUrl, array $postData = [])
182
    {
183
        $postDataMultipart = [];
184
        foreach ($postData as $key => $value) {
185
            if (is_array($value)) {
186
                $index = 0;
187
                foreach ($value as $subValue) {
188
                    $postDataMultipart[] = [
189
                        'name'     => sprintf('%s[%d]', $key, $index++),
190
                        'contents' => $subValue,
191
                    ];
192
                }
193
            } else {
194
                $postDataMultipart[] = [
195
                    'name'     => $key,
196
                    'contents' => $value,
197
                ];
198
            }
199
        }
200
201
        return $this->send('POST', $endpointUrl, $postDataMultipart);
202
    }
203
204
    /**
205
     * @param $uri
206
     *
207
     * @return string
208
     */
209
    private function getApiUrl($uri)
210
    {
211
        return $this->generateEndpoint($this->apiHost).$uri;
212
    }
213
214
    /**
215
     * @param string $apiEndpoint
216
     *
217
     * @return string
218
     */
219
    private function generateEndpoint($apiEndpoint)
220
    {
221
        return sprintf('%s/', $apiEndpoint);
222
    }
223
}
224