Completed
Push — master ( 2baebf...b22d69 )
by smiley
01:43
created

CurlClient   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Importance

Changes 0
Metric Value
dl 0
loc 49
rs 10
c 0
b 0
f 0
wmc 3
lcom 1
cbo 9

1 Method

Rating   Name   Duplication   Size   Complexity  
A sendRequest() 0 35 3
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