HttpTrait::getResponse()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
namespace Stevenmaguire\Yelp\Tool;
4
5
use \Exception;
6
use GuzzleHttp\Client as HttpClient;
7
use GuzzleHttp\Exception\BadResponseException;
8
use GuzzleHttp\Psr7\Request;
9
use GuzzleHttp\Psr7\Uri;
10
use Psr\Http\Message\RequestInterface;
11
use Psr\Http\Message\ResponseInterface;
12
use Stevenmaguire\Yelp\Exception\ClientConfigurationException;
13
use Stevenmaguire\Yelp\Exception\HttpException;
14
15
trait HttpTrait
16
{
17
    /**
18
     * API host url
19
     *
20
     * @var string
21
     */
22
    protected $apiHost;
23
24
    /**
25
     * HTTP client
26
     *
27
     * @var \GuzzleHttp\Client
28
     */
29
    protected $httpClient;
30
31
    /**
32
     * HTTP scheme
33
     *
34
     * @var string
35
     */
36
    protected $scheme;
37
38
    /**
39
     * Prepares and appends parameters, if provided, to the given url.
40
     *
41
     * @param  string     $url
42
     * @param  array      $parameters
43
     * @param  string[]   $options
44
     *
45
     * @return string
46
     */
47 26
    protected function appendParametersToUrl($url, array $parameters = array(), array $options = array())
48
    {
49 26
        $url = rtrim($url, '?');
50 26
        $queryString = $this->prepareQueryParams($parameters, $options);
51
52 26
        if ($queryString) {
53 22
            $uri = new Uri($url);
54 22
            $existingQuery = $uri->getQuery();
55 22
            $updatedQuery = empty($existingQuery) ? $queryString : $existingQuery . '&' . $queryString;
56 22
            $url = (string) $uri->withQuery($updatedQuery);
57 11
        }
58
59 26
        return $url;
60
    }
61
62
    /**
63
     * Flattens given array into comma separated value.
64
     *
65
     * @param  mixed   $input
66
     *
67
     * @return string|mixed
68
     */
69 2
    private function arrayToCsv($input)
70
    {
71 2
        if (is_array($input)) {
72 2
            $input = implode(',', $input);
73 1
        }
74
75 2
        return $input;
76
    }
77
78
    /**
79
     * Coerces given value into boolean and returns string representation
80
     *
81
     * @param  boolean   $value
82
     *
83
     * @return string
84
     */
85 4
    private function getBoolString($value)
86
    {
87 4
        return (bool) $value ? 'true' : 'false';
88
    }
89
90
    /**
91
     * Returns the yelp client's http client to the given http client. Client.
92
     *
93
     * @return  GuzzleHttp\Client|null
94
     */
95 42
    public function getHttpClient()
96
    {
97 42
        return $this->httpClient;
98
    }
99
100
    /**
101
     * Creates a PSR-7 Request instance.
102
     *
103
     * @param  null|string $method HTTP method for the request.
104
     * @param  null|string $uri URI for the request.
105
     * @param  array $headers Headers for the message.
106
     * @param  string|resource|StreamInterface $body Message body.
107
     * @param  string $version HTTP protocol version.
108
     *
109
     * @return Request
110
     */
111 28
    public function getRequest(
112
        $method,
113
        $uri,
114
        array $headers = [],
115
        $body = null,
116
        $version = '1.1'
117
    ) {
118 28
        $uri = new Uri($uri);
119
120 28
        if (!$uri->getHost()) {
121 28
            $uri = $uri->withHost($this->apiHost);
122 14
        }
123
124 28
        if (!$uri->getScheme()) {
125 28
            $uri = $uri->withScheme(($this->scheme ?: 'https'));
126 14
        }
127
128 28
        return new Request($method, $uri, $headers, $body, $version);
129
    }
130
131
    /**
132
     * Sends a request instance and returns a response instance.
133
     *
134
     * WARNING: This method does not attempt to catch exceptions caused by HTTP
135
     * errors! It is recommended to wrap this method in a try/catch block.
136
     *
137
     * @param  RequestInterface $request
138
     * @return ResponseInterface
139
     * @throws Stevenmaguire\Yelp\Exception\HttpException
140
     */
141 14
    public function getResponse(RequestInterface $request)
142
    {
143
        try {
144 14
            return $this->getHttpClient()->send($request);
145 2
        } catch (BadResponseException $e) {
146 7
            $exception = new HttpException($e->getMessage());
147
148 3
            throw $exception->setResponseBody((string) $e->getResponse()->getBody());
149
        }
150 1
    }
151
152
    /**
153
     * Provides a hook that handles the response before returning to the consumer.
154
     *
155
     * @param ResponseInterface $response
156
     *
157
     * @return  ResponseInterface
158
     */
159
    abstract protected function handleResponse(ResponseInterface $response);
160
161
    /**
162
     * Updates query params array to apply yelp specific formatting rules.
163
     *
164
     * @param  array      $params
165
     * @param  string[]   $csvParams
166
     *
167
     * @return string
168
     */
169
    protected function prepareQueryParams($params = [], $csvParams = [])
170
    {
171 26
        array_walk($params, function ($value, $key) use (&$params, $csvParams) {
172 22
            if (is_bool($value)) {
173 4
                $params[$key] = $this->getBoolString($value);
174 2
            }
175
176 22
            if (in_array($key, $csvParams)) {
177 2
                $params[$key] = $this->arrayToCsv($value);
178 1
            }
179 26
        });
180
181 26
        return http_build_query($params);
182
    }
183
184
    /**
185
     * Makes a request to the Yelp API and returns the response
186
     *
187
     * @param    RequestInterface $request
188
     *
189
     * @return   stdClass The JSON response from the request
190
     * @throws   Stevenmaguire\Yelp\Exception\ClientConfigurationException
191
     * @throws   Stevenmaguire\Yelp\Exception\HttpException
192
     */
193 24
    protected function processRequest(RequestInterface $request)
194
    {
195 24
        $response = $this->handleResponse($this->getResponse($request));
196
197 20
        return json_decode($response->getBody());
198
    }
199
200
    /**
201
     * Updates the yelp client's http client to the given http client. Client.
202
     *
203
     * @param HttpClient  $client
204
     *
205
     * @return  mixed
206
     */
207 42
    public function setHttpClient(HttpClient $client)
208
    {
209 42
        $this->httpClient = $client;
210
211 42
        return $this;
212
    }
213
}
214