This repository was archived by the owner on May 4, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.php
More file actions
360 lines (315 loc) · 7.88 KB
/
Client.php
File metadata and controls
360 lines (315 loc) · 7.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
<?php
namespace http;
require_once 'Response.php';
require_once 'Exception.php';
require_once 'Uri.php';
class Client {
const REQUEST_METHOD_GET = 'GET';
const REQUEST_METHOD_POST = 'POST';
/**
* POST data encoding methods
*/
const ENC_URLENCODED = 'application/x-www-form-urlencoded';
const ENC_FORMDATA = 'multipart/form-data';
/**
* @var Uri|null
*/
protected $uri;
/**
* @var resource|null
*/
protected $context;
/**
* @var resource|null
*/
protected $socket;
/**
* @var array
*/
protected $auth = array('username' => null, 'password' => null);
protected $parametersGet = array();
protected $parametersPost = array();
protected $headers = array();
/**
* Load response error string.
* Is null if there was no error while response loading
*
* @var string|null
*/
protected $loadResponseErrorStr;
/**
* Load response error code.
* Is null if there was no error while response loading
*
* @var int|null
*/
protected $loadResponseErrorCode;
/**
* @var int[]|string[]
*/
protected $config = array(
'fetchBody' => true,
'fetchHeaders' => true,
'timeout' => 10
);
/**
* @param \http\Uri|string|null $uri
*/
public function __construct($uri = null) {
if ($uri !== null) {
$this->setUri($uri);
}
}
/**
* @param string $method
* @return \http\Response
*/
public function request($method = self::REQUEST_METHOD_GET) {
// Warnings and errors are suppressed
set_error_handler(array($this, 'loadFileErrorHandler'));
$this->setConfig(array('method' => $method));
$this->createContext();
$this->connect();
$response = new Response($this->fetchHeaders(), $this->fetchBody());
$this->disconnect();
restore_error_handler();
return $response;
}
/**
* @throws \http\Exception
* @return array
*/
protected function fetchHeaders() {
if ($this->getConfig('fetchHeaders')) {
$metaData = stream_get_meta_data($this->socket);
if ($this->loadResponseErrorStr !== null) {
$this->disconnect();
throw new Exception("Can't fetch response headers from {$this->getUrl()} [{$this->loadResponseErrorStr}]");
}
$headers = $metaData['wrapper_data'];
} else {
$headers = array('HTTP/1.0 200 OK');
}
return $headers;
}
/**
* @throws \http\Exception
* @return string
*/
protected function fetchBody() {
if ($this->getConfig('fetchBody')) {
$body = stream_get_contents($this->socket);
if ($this->loadResponseErrorStr !== null) {
$this->disconnect();
throw new Exception("Can't fetch response content from {$this->getUrl()} [{$this->loadResponseErrorStr}]", $this->loadResponseErrorCode);
}
} else {
$body = '';
}
return $body;
}
/**
* @throws \http\Exception
* @return null|resource
*/
protected function createContext() {
$httpOptions = array(
'method' => $this->getConfig('method'),
'timeout' => $this->getConfig('timeout'),
'max_redirects' => 0,
'ignore_errors' => 1,
'header' => $this->prepareHeaders()
);
// setup POST-paramteres
if ($this->getConfig('method') == self::REQUEST_METHOD_POST) {
$httpOptions['content'] = http_build_query($this->parametersPost, null, '&');
}
$this->context = stream_context_create(array(
'http' => $httpOptions
));
if ($this->loadResponseErrorStr !== null) {
throw new Exception($this->loadResponseErrorStr, $this->loadResponseErrorCode);
}
return $this->context;
}
protected function prepareHeaders() {
$headers = '';
$this->setHeader('Host', $this->getUrl()->getHost());
if ($username = $this->getAuth('username')) {
$this->setHeader('Authorization', "Basic " . base64_encode($username . ':' . $this->getAuth('password', '')));
// $this->setHeader('Authorization', "Basic " . base64_encode(urlencode($username) . ':' . urlencode($this->getAuth('password', ''))));
}
$this->setHeader('Content-Type', $this->getConfig('method') == self::REQUEST_METHOD_POST? self::ENC_URLENCODED: self::ENC_FORMDATA);
foreach($this->headers as $name => $value) {
$headers .= "{$name}: {$value}\n";
}
return $headers;
}
/**
* @param string $name
* @param string|null $value
* @return \http\Client
*/
public function setHeader($name, $value) {
if ($value === null && array_key_exists($name, $this->headers)) {
unset($this->headers[$name]);
} else {
$this->headers[$name] = $value;
}
return $this;
}
/**
* @throws \http\Exception
* @return resource
*/
protected function connect() {
// setup GET-parameters to URI
$uri = clone $this->getUrl();
$query = $uri->getQuery();
if (!empty($query)) {
$query .= '&';
}
$query .= http_build_query($this->parametersGet);
$uri->setQuery($query);
// connect to http-server
$this->socket = fopen((string) $uri, 'r', null, $this->context);
if ($this->loadResponseErrorStr !== null) {
$this->disconnect();
throw new Exception("Can't connect to {$this->getUrl()} [{$this->loadResponseErrorStr}]", $this->loadResponseErrorCode);
}
return $this->socket;
}
/**
* @return \http\Client
*/
protected function disconnect() {
if (is_resource($this->socket)) {
fclose($this->socket);
}
return $this;
}
/**
* Handle any errors from simplexml_load_file or parse_ini_file
*
* @param integer $errno
* @param string $errstr
* @param string $errfile
* @param integer $errline
*/
public function loadFileErrorHandler($errno, $errstr, $errfile, $errline) {
$this->loadResponseErrorCode = $errno;
if ($this->loadResponseErrorStr === null) {
$this->loadResponseErrorStr = $errstr;
} else {
$this->loadResponseErrorStr .= (PHP_EOL . $errstr);
}
}
/**
* @param string|null $username
* @param string|null $password
* @return \http\Client
*/
public function setAuth($username, $password) {
$this->auth = array(
'username' => $username === null? null: (string) $username,
'password' => $password === null? null: (string) $password
);
return $this;
}
/**
* @param string|null $field
* @return array|string
*/
public function getAuth($field = null) {
if ($field === null) {
return $this->auth;
} else if (array_key_exists($field, $this->auth)) {
return $this->auth[$field];
}
return null;
}
/**
* @param array $config
* @return \http\Client
*/
public function setConfig(array $config) {
$this->config = array_merge($this->config, $config);
return $this;
}
/**
* @param null $parameter
* @return array|string|int|null
*/
public function getConfig($parameter = null) {
if ($parameter === null) {
return $this->config;
} else if (array_key_exists($parameter, $this->config)) {
return $this->config[$parameter];
}
return null;
}
/**
* @param \http\Uri|string $uri
* @return \http\Client;
*/
public function setUri($uri) {
if (!$uri instanceof Uri) {
$uri = new Uri($uri);
}
$this->uri = $uri;
return $this;
}
/**
*
* @throws \http\Exception
* @return \http\Uri|null
*/
public function getUrl() {
if (!$this->uri instanceof Uri) {
throw new Exception('RequestUri is not setup');
}
return $this->uri;
}
/**
* @param bool $resetHeaders
* @return \http\Client
*/
public function resetParameters($resetHeaders = false) {
$this->parametersGet = array();
$this->parametersPost = array();
if ($resetHeaders) {
$this->headers = array();
}
return $this;
}
/**
* @param string[]|string $name
* @param string|null $value
* @return \http\Client
*/
public function setParameterGet($name, $value = null) {
if (is_array($name)) {
foreach($name as $k => $v) {
$this->setParameterGet($k, $v);
}
} else {
$this->parametersGet[$name] = $value;
}
return $this;
}
/**
* @param string[]|string $name
* @param string|null $value
* @return \http\Client
*/
public function setParameterPost($name, $value = null) {
if (is_array($name)) {
foreach($name as $k => $v) {
$this->setParameterPost($k, $v);
}
} else {
$this->parametersPost[$name] = $value;
}
return $this;
}
}