Completed
Push — master ( 7d3739...cdb80e )
by keika
01:59
created

Request::setQuery()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3.009

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 17
ccs 9
cts 10
cp 0.9
rs 9.4286
cc 3
eloc 9
nc 3
nop 1
crap 3.009
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 43
    public function __construct()
32
    {
33 43
        $this->baseURI = '';
34 43
        $this->method = 'GET';
35 43
        $this->uri = '';
36 43
        $this->headers = array();
37 43
        $this->body = null;
38 43
        $this->json = null;
39 43
        $this->query = '';
40 43
    }
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 35
    public function exec()
52
    {
53 35
        $options = array();
54
55 35
        if ($this->body !== null) {
56 2
            $options['body'] = $this->body;
57 2
        }
58 35
        if ($this->json !== null) {
59 9
            $options['json'] = $this->json;
60 9
        }
61 35
        if (0 < count($this->headers)) {
62 35
            $options['headers'] = $this->headers;
63 35
        }
64
65 35
        $client = getenv('IS_TEST') ? $this->createMockClient() : new Client(['base_uri' => $this->baseURI]);
66
67
        try {
68 35
            $response = $client->request($this->method, $this->uri.$this->query, $options);
69 35
            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 36
    public function setMethod($method)
84
    {
85 36
        $this->method = strtoupper($method);
86 36
        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 36
    public function setBaseURI($baseURI)
99
    {
100 36
        $this->baseURI = $baseURI;
101 36
        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 36
    public function setURI($uri)
115
    {
116 36
        $this->uri = $uri;
117 36
        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 32
    public function setAccept($value)
144
    {
145 32
        $this->headers['Accept'] = $value;
146 32
        return $this;
147
    }
148
149
    /**
150
     * Set 'Content-Type' request header
151
     *
152
     * @param string $value
153
     * @return $this
154
     */
155 5
    public function setContentType($value)
156
    {
157 5
        $this->headers['Content-Type'] = $value;
158 5
        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 10
    public function setJson(array $array)
184
    {
185 10
        $this->json = $array;
186 10
        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 1
    public function setQuery(array $array)
198
    {
199 1
        if (sizeof($array) === 0) {
200
            return $this;
201
        }
202
203 1
        $query = '?';
204
205 1
        foreach ($array as $item => $value) {
206 1
            $query .= $item . '=' . $value . '&';
207 1
        }
208
209 1
        $this->query = mb_substr($query, 0, -1, "UTF-8");
210 1
        echo $this->query;
211
212 1
        return $this;
213
    }
214
215
    /**
216
     * Set 'X-Auth-Token' request header.
217
     *
218
     * @param string $token
219
     * @return $this
220
     */
221 28
    public function setToken($token)
222
    {
223 28
        $this->headers['X-Auth-Token'] = $token;
224 28
        return $this;
225
    }
226
227 35
    private function createMockClient()
228
    {
229 35
        $body = '{"checkKey": "checkValue", "access": {"token": {"id": "sample00d88246078f2bexample788f7"}}}';
230
231
        $mockResponse = [
232 35
            new Psr7Response(200, [], $body)
233 35
        ];
234 35
        $mockHandler = new MockHandler($mockResponse);
235 35
        $handlerStack = HandlerStack::create($mockHandler);
236 35
        return new Client(['handler' => $handlerStack]);
237
    }
238
}
239