Client::buildHeaders()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 7
rs 9.4285
cc 1
eloc 4
nc 1
nop 0
1
<?php
2
3
namespace VerticalResponse;
4
5
use Psr\Http\Message\ResponseInterface;
6
use Psr\Http\Message\StreamInterface;
7
use VerticalResponse\Client\Exception;
8
use VerticalResponse\Client\HttpClientInterface;
9
use VerticalResponse\Client\HttpException;
10
use VerticalResponse\Client\RequestProviderInterface;
11
12
class Client
13
{
14
    const LOCATION = 'https://vrapi.verticalresponse.com/api/v1/';
15
16
    /**
17
     * @var string
18
     */
19
    private $accessToken;
20
21
    /**
22
     * @var RequestProviderInterface
23
     */
24
    private $requestProvider;
25
26
    /**
27
     * @var HttpClientInterface
28
     */
29
    private $client;
30
31
    /**
32
     * Client constructor.
33
     *
34
     * @param string                        $accessToken
35
     * @param HttpClientInterface|null      $client
36
     * @param RequestProviderInterface|null $requestProvider
37
     */
38
    public function __construct(
39
        $accessToken,
40
        HttpClientInterface $client = null,
41
        RequestProviderInterface $requestProvider = null
42
    ) {
43
        $this->accessToken = $accessToken;
44
        if (!$client && !class_exists('VerticalResponse\Client\GuzzleClient')) {
45
            throw new \InvalidArgumentException('An HttpClient is required, or verticalresponse-guzzle installed');
46
        }
47
        if (!$requestProvider && !class_exists('VerticalResponse\Client\GuzzleRequestFactory')) {
48
            throw new \InvalidArgumentException('A RequestProvider is required, or verticalresponse-guzzle installed');
49
        }
50
        $this->requestProvider = $requestProvider ?: new \VerticalResponse\Client\GuzzleRequestFactory();
51
        $this->client = $client ?: new \VerticalResponse\Client\GuzzleClient(['base_uri' => static::LOCATION]);
52
    }
53
54
    /**
55
     * @param string $url
56
     * @param array  $parameters
57
     *
58
     * @return \stdClass
59
     * @throws Exception
60
     * @throws HttpException
61
     */
62
    public function get($url, $parameters = [])
63
    {
64
        $query = $this->buildQuery($url, $parameters);
65
        $url = static::LOCATION.$url.(strpos($url, '?') !== false ? '&' : '?').$query;
66
        $headers = $this->buildHeaders();
67
68
        $request = $this->requestProvider->createRequest('GET', $url, $headers);
69
        $response = $this->client->send($request);
70
71
        // Throw any errors we have before continuing
72
        $this->errorCheckResponse($response);
73
74
        return json_decode($this->streamToString($response->getBody()));
75
    }
76
77
    /**
78
     * @param string $url
79
     * @param array  $parameters
80
     *
81
     * @return \stdClass
82
     * @throws Exception
83
     * @throws HttpException
84
     */
85
    public function post($url, $parameters = [])
86
    {
87
        $url = static::LOCATION.$url;
88
        $headers = $this->buildHeaders();
89
90
        $request = $this->requestProvider->createRequest('POST', $url, $headers, json_encode($parameters));
91
        $response = $this->client->send($request);
92
93
        $this->errorCheckResponse($response);
94
95
        return json_decode($this->streamToString($response->getBody()));
96
    }
97
98
    /**
99
     * @param string $url
100
     * @param array  $parameters
101
     *
102
     * @return string
103
     */
104
    protected function buildQuery($url, $parameters)
0 ignored issues
show
Unused Code introduced by
The parameter $url is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
105
    {
106
        return http_build_query($parameters);
107
    }
108
109
    /**
110
     * @return string[]
111
     */
112
    protected function buildHeaders()
113
    {
114
        return [
115
            'Content-Type'  => 'application/json; charset=utf-8',
116
            'Authorization' => "Bearer {$this->accessToken}",
117
        ];
118
    }
119
120
    /**
121
     * @param ResponseInterface $response
122
     *
123
     * @return void
124
     * @throws Exception
125
     * @throws HttpException
126
     */
127
    protected function errorCheckResponse(ResponseInterface $response)
128
    {
129
        $body = $response->getBody();
130
131
        if ($response->getStatusCode() >= 400) {
132
            throw new HttpException($response);
133
        }
134
135
        $responseObject = @json_decode($this->streamToString($body));
136
        if (!isset($responseObject)) {
137
            throw new Exception('JSON returned is not valid', $response);
138
        }
139
140
        if (isset($responseObject->error)) {
141
            throw new Exception($responseObject->error, $response);
142
        }
143
    }
144
145
    /**
146
     * @param StreamInterface $stream
147
     *
148
     * @return string
149
     */
150
    protected function streamToString(StreamInterface $stream)
151
    {
152
        $stream->rewind();
153
        return $stream->getContents();
154
    }
155
156
    /** @return string */
157
    public function getLocation()
158
    {
159
        return static::LOCATION;
160
    }
161
}
162