Completed
Pull Request — master (#20)
by Steven
12:12
created

HttpTrait::arrayToCsv()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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