Completed
Pull Request — master (#3)
by keika
02:08
created

Request::setQuery()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 2
Bugs 0 Features 2
Metric Value
c 2
b 0
f 2
dl 0
loc 16
ccs 9
cts 9
cp 1
rs 9.4286
cc 3
eloc 8
nc 3
nop 1
crap 3
1
<?php
2
3
namespace keika299\ConohaAPI\Common\Network;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\Handler\MockHandler;
7
use GuzzleHttp\HandlerStack;
8
use GuzzleHttp\Psr7\Response as Psr7Response;
9
use keika299\ConohaAPI\Common\Exceptions\Network\ExceptionFactory;
10
11
/**
12
 * Class Request
13
 *
14
 * Create API request and exec it.
15
 *
16
 * @package keika299\ConohaAPI\Common\Network
17
 */
18
class Request
19
{
20
    private $baseURI;
21
    private $method;
22
    private $uri;
23
    private $headers;
24
    private $body;
25
    private $json;
26
    private $query;
27
28
    /**
29
     * Request constructor.
30
     */
31 82
    public function __construct()
32
    {
33 82
        $this->baseURI = '';
34 82
        $this->method = 'GET';
35 82
        $this->uri = '';
36 82
        $this->headers = array();
37 82
        $this->body = null;
38 82
        $this->json = null;
39 82
        $this->query = '';
40 82
    }
41
42
    /**
43
     * Exec API request.
44
     *
45
     * This function have to run after set all params.
46
     * If $_ENV['IS_TEST'] has value, this function return mock.
47
     *
48
     * @return Response
49
     * @throws \keika299\ConohaAPI\Common\Exceptions\IConohaAPIException
50
     */
51 74
    public function exec()
52
    {
53 74
        $options = array();
54
55 74
        if ($this->body !== null) {
56 2
            $options['body'] = $this->body;
57 2
        }
58 74
        if ($this->json !== null) {
59 25
            $options['json'] = $this->json;
60 25
        }
61 74
        if (0 < count($this->headers)) {
62 74
            $options['headers'] = $this->headers;
63 74
        }
64
65 74
        $client = getenv('IS_TEST') ? $this->createMockClient() : new Client(['base_uri' => $this->baseURI]);
66
67
        try {
68 74
            $response = $client->request($this->method, $this->uri.$this->query, $options);
69 74
            return new Response($response);
70
        }
71
        catch (\Exception $e) {
72
            throw ExceptionFactory::build($e);
73
        }
74
    }
75
76
    /**
77
     * Set request method.
78
     * $method allow HTTP/1.1 request methods.
79
     *
80
     * @param string $method
81
     * @return $this
82
     */
83 75
    public function setMethod($method)
84
    {
85 75
        $this->method = strtoupper($method);
86 75
        return $this;
87
    }
88
89
    /**
90
     * Set base URI.
91
     *
92
     * $baseURI usually begin 'https://' or 'http://'.
93
     * $baseURI expect last character is not with '/'.
94
     *
95
     * @param string $baseURI
96
     * @return $this
97
     */
98 75
    public function setBaseURI($baseURI)
99
    {
100 75
        $this->baseURI = $baseURI;
101 75
        return $this;
102
    }
103
104
    /**
105
     * Set URI.
106
     *
107
     * $uri is NOT completely URI.
108
     * This param connect with base URI.
109
     * $uri expect to start with '/'.
110
     *
111
     * @param string $uri
112
     * @return $this
113
     */
114 75
    public function setURI($uri)
115
    {
116 75
        $this->uri = $uri;
117 75
        return $this;
118
    }
119
120
    /**
121
     * Add request header value.
122
     *
123
     * $key is parameter, and $value is value of that parameter.
124
     * You want to add 'X-Auth-Token', you can use setToken func.
125
     * You want to add 'Accept', you can use setAccept func.
126
     *
127
     * @param string $key
128
     * @param string $value
129
     * @return $this
130
     */
131 1
    public function addHeader($key, $value)
132
    {
133 1
        $this->headers[$key] = $value;
134 1
        return $this;
135
    }
136
137
    /**
138
     * Set 'Accept' request header.
139
     *
140
     * @param string $value
141
     * @return $this
142
     */
143 71
    public function setAccept($value)
144
    {
145 71
        $this->headers['Accept'] = $value;
146 71
        return $this;
147
    }
148
149
    /**
150
     * Set 'Content-Type' request header
151
     *
152
     * @param string $value
153
     * @return $this
154
     */
155 6
    public function setContentType($value)
156
    {
157 6
        $this->headers['Content-Type'] = $value;
158 6
        return $this;
159
    }
160
161
    /**
162
     * Set request body.
163
     *
164
     * You can use this function when request 'POST' or 'PUT' method.
165
     *
166
     * @param string $body
167
     * @return $this
168
     */
169 3
    public function setBody($body)
170
    {
171 3
        $this->body = $body;
172 3
        return $this;
173
    }
174
175
    /**
176
     * Set request Json.
177
     *
178
     * Array transform to json data, and set request body.
179
     *
180
     * @param array $array
181
     * @return $this
182
     */
183 26
    public function setJson(array $array)
184
    {
185 26
        $this->json = $array;
186 26
        return $this;
187
    }
188
189
    /**
190
     * Set request URI query.
191
     *
192
     * $array have to be associative array.
193
     *
194
     * @param array $array
195
     * @return $this
196
     */
197 8
    public function setQuery(array $array)
198
    {
199 8
        if (sizeof($array) === 0) {
200 7
            return $this;
201
        }
202
203 8
        $query = '?';
204
205 8
        foreach ($array as $item => $value) {
206 8
            $query .= $item . '=' . $value . '&';
207 8
        }
208
209 8
        $this->query = mb_substr($query, 0, -1, "UTF-8");
210
211 8
        return $this;
212
    }
213
214
    /**
215
     * Set 'X-Auth-Token' request header.
216
     *
217
     * @param string $token
218
     * @return $this
219
     */
220 66
    public function setToken($token)
221
    {
222 66
        $this->headers['X-Auth-Token'] = $token;
223 66
        return $this;
224
    }
225
226 74
    private function createMockClient()
227
    {
228 74
        $body = '{"checkKey": "checkValue", "access": {"token": {"id": "sample00d88246078f2bexample788f7"}}}';
229
230
        $mockResponse = [
231 74
            new Psr7Response(200, [], $body)
232 74
        ];
233 74
        $mockHandler = new MockHandler($mockResponse);
234 74
        $handlerStack = HandlerStack::create($mockHandler);
235 74
        return new Client(['handler' => $handlerStack]);
236
    }
237
}
238