CurlClient::getCurlClient()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 16
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 13
nc 1
nop 1
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * @category    Brownie/CartsGuru
4
 * @author      Brownie <[email protected]>
5
 * @license     http://www.gnu.org/copyleft/lesser.html
6
 */
7
8
namespace Brownie\CartsGuru\HTTPClient;
9
10
use Brownie\CartsGuru\Exception\ClientException;
11
12
/**
13
 * HTTP client based on cURL.
14
 */
15
class CurlClient implements Client
16
{
17
18
    /**
19
     * Performs a network request in CartsGuru.
20
     * Returns the response from CartsGuru.
21
     *
22
     * @param Query       $query        HTTP client query params.
23
     *
24
     * @throws ClientException
25
     *
26
     * @return Response
27
     */
28
    public function httpRequest(Query $query)
29
    {
30
        $curl = $this->getCurlClient($query);
31
32
        /**
33
         * Executes a network resource request.
34
         */
35
        $responseBody = curl_exec($curl);
36
37
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
38
39
        /**
40
         * Network error checking.
41
         */
42
        if ((0 != curl_errno($curl)) || !is_string($responseBody)) {
43
            throw new ClientException(curl_error($curl));
44
        }
45
46
        $runtime = curl_getinfo($curl, CURLINFO_TOTAL_TIME);
47
48
        curl_close($curl);
49
50
        $response = new Response();
51
        return $response
52
            ->setBody($responseBody)
53
            ->setHttpCode($httpCode)
54
            ->setRuntime($runtime);
55
    }
56
57
    /**
58
     * Curl init.
59
     *
60
     * @param Query       $query        HTTP client query params.
61
     *
62
     * @return resource
63
     */
64
    private function getCurlClient(Query $query)
65
    {
66
        $curl = curl_init($query->getApiUrl());
67
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($query->getData()));
68
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $query->getMethod());
69
        curl_setopt($curl, CURLOPT_TIMEOUT, $query->getTimeOut());
70
        curl_setopt($curl, CURLOPT_NOPROGRESS, true);
71
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
72
        curl_setopt($curl, CURLOPT_URL, $query->getApiUrl());
73
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
74
            'Connection: close',
75
            'Accept: application/json',
76
            'Content-Type: application/json; charset=utf-8',
77
            'x-auth-key: ' . $query->getXAuthKey()
78
        ));
79
        return $curl;
80
    }
81
}
82