|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Class HTTPClient |
|
4
|
|
|
* |
|
5
|
|
|
* @filesource HTTPClient.php |
|
6
|
|
|
* @created 27.08.2018 |
|
7
|
|
|
* @package chillerlan\HTTP |
|
8
|
|
|
* @author smiley <[email protected]> |
|
9
|
|
|
* @copyright 2018 smiley |
|
10
|
|
|
* @license MIT |
|
11
|
|
|
*/ |
|
12
|
|
|
|
|
13
|
|
|
namespace chillerlan\HTTP\Psr18; |
|
14
|
|
|
|
|
15
|
|
|
use Psr\Http\Message\{RequestInterface, ResponseInterface}; |
|
16
|
|
|
|
|
17
|
|
|
class CurlClient extends HTTPClientAbstract{ |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* Sends a PSR-7 request. |
|
21
|
|
|
* |
|
22
|
|
|
* @param \Psr\Http\Message\RequestInterface $request |
|
23
|
|
|
* |
|
24
|
|
|
* @return \Psr\Http\Message\ResponseInterface |
|
25
|
|
|
* |
|
26
|
|
|
* @throws \Psr\Http\Client\ClientExceptionInterface If an error happens during processing the request. |
|
27
|
|
|
* @throws \Exception If processing the request is impossible (eg. bad configuration). |
|
28
|
|
|
*/ |
|
29
|
|
|
public function sendRequest(RequestInterface $request):ResponseInterface{ |
|
30
|
|
|
/** @var \chillerlan\HTTP\Psr18\CurlHandle $handle */ |
|
31
|
|
|
$handle = new $this->options->curlHandle($request, $this->responseFactory->createResponse(), $this->options); |
|
32
|
|
|
$handle->init(); |
|
33
|
|
|
|
|
34
|
|
|
curl_exec($handle->curl); |
|
35
|
|
|
|
|
36
|
|
|
$errno = curl_errno($handle->curl); |
|
37
|
|
|
|
|
38
|
|
|
if($errno !== CURLE_OK){ |
|
39
|
|
|
$error = curl_error($handle->curl); |
|
40
|
|
|
|
|
41
|
|
|
$network_errors = [ |
|
42
|
|
|
CURLE_COULDNT_RESOLVE_PROXY, |
|
43
|
|
|
CURLE_COULDNT_RESOLVE_HOST, |
|
44
|
|
|
CURLE_COULDNT_CONNECT, |
|
45
|
|
|
CURLE_OPERATION_TIMEOUTED, |
|
46
|
|
|
CURLE_SSL_CONNECT_ERROR, |
|
47
|
|
|
CURLE_GOT_NOTHING, |
|
48
|
|
|
]; |
|
49
|
|
|
|
|
50
|
|
|
$this->logger->error('cURL error #'.$errno.': '.$error); |
|
51
|
|
|
|
|
52
|
|
|
if(in_array($errno, $network_errors, true)){ |
|
53
|
|
|
throw new NetworkException($error, $request); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
throw new RequestException($error, $request); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
$handle->close(); |
|
60
|
|
|
$handle->response->getBody()->rewind(); |
|
61
|
|
|
|
|
62
|
|
|
return $handle->response; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
} |
|
66
|
|
|
|