Completed
Push — master ( 0fa021...08bd3f )
by smiley
01:32
created

CurlClient::request()   C

Complexity

Conditions 9
Paths 93

Size

Total Lines 58
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 58
rs 6.9928
c 0
b 0
f 0
cc 9
eloc 32
nc 93
nop 5

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Class CurlClient
4
 *
5
 * @filesource   CurlClient.php
6
 * @created      21.10.2017
7
 * @package      chillerlan\HTTP
8
 * @author       Smiley <[email protected]>
9
 * @copyright    2017 Smiley
10
 * @license      MIT
11
 */
12
13
namespace chillerlan\HTTP;
14
15
use chillerlan\Traits\ContainerInterface;
16
17
/**
18
 * @property resource $http
19
 */
20
class CurlClient extends HTTPClientAbstract{
21
22
	/**
23
	 * @var \stdClass
24
	 */
25
	protected $responseHeaders;
26
27
	/**
28
	 * CurlClient constructor.
29
	 *
30
	 * @param \chillerlan\Traits\ContainerInterface $options
31
	 *
32
	 * @throws \chillerlan\HTTP\HTTPClientException
33
	 */
34
	public function __construct(ContainerInterface $options){
35
		parent::__construct($options);
36
37 View Code Duplication
		if(!isset($this->options->ca_info) || !is_file($this->options->ca_info)){
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
38
			throw new HTTPClientException('invalid CA file');
39
		}
40
41
		$this->http = curl_init();
42
43
		curl_setopt_array($this->http, [
44
			CURLOPT_HEADER         => false,
45
			CURLOPT_RETURNTRANSFER => true,
46
			CURLOPT_PROTOCOLS      => CURLPROTO_HTTP|CURLPROTO_HTTPS,
47
			CURLOPT_CAINFO         => $this->options->ca_info,
48
			CURLOPT_SSL_VERIFYPEER => true,
49
			CURLOPT_SSL_VERIFYHOST => 2,
50
			CURLOPT_TIMEOUT        => 5,
51
			CURLOPT_USERAGENT      => $this->options->user_agent,
52
		]);
53
54
		curl_setopt_array($this->http, $this->options->curl_options);
55
	}
56
57
	/** @inheritdoc */
58
	protected function getResponse():HTTPResponseInterface{
59
		$this->responseHeaders = new \stdClass;
60
61
		$headers = $this->normalizeRequestHeaders($this->requestHeaders);
62
		$options = [CURLOPT_CUSTOMREQUEST => $this->requestMethod];
63
64
		if(in_array($this->requestMethod, ['PATCH', 'POST', 'PUT', 'DELETE'], true)){
65
66
			if($this->requestMethod === 'POST'){
67
				$options = [CURLOPT_POST => true];
68
69
				if(!isset($headers['Content-type']) && is_array($this->requestBody)){
70
					$headers += ['Content-type: application/x-www-form-urlencoded'];
71
					$this->requestBody = http_build_query($this->requestBody, '', '&', PHP_QUERY_RFC1738);
72
				}
73
			}
74
75
			$options += [CURLOPT_POSTFIELDS => $this->requestBody];
76
		}
77
78
		$headers += [
79
			'Host: '.$this->parsedURL['host'],
80
			'Connection: close',
81
		];
82
83
		$url = $this->requestURL.(!empty($this->requestParams) ? '?'.$this->buildQuery($this->requestParams) : '');
84
85
		$options += [
86
			CURLOPT_URL => $url,
87
			CURLOPT_HTTPHEADER => $headers,
88
			CURLOPT_HEADERFUNCTION => [$this, 'headerLine'],
89
		];
90
91
		curl_setopt_array($this->http, $options);
92
93
		$response = curl_exec($this->http);
94
95
		return new HTTPResponse([
96
			'url'     => $url,
97
			'headers' => $this->responseHeaders,
98
			'body'    => $response,
99
		]);
100
	}
101
102
	/**
103
	 * @param resource $curl
104
	 * @param string   $header_line
105
	 *
106
	 * @return int
107
	 *
108
	 * @link http://php.net/manual/function.curl-setopt.php CURLOPT_HEADERFUNCTION
109
	 */
110
	protected function headerLine(/** @noinspection PhpUnusedParameterInspection */$curl, $header_line){
111
		$header = explode(':', $header_line, 2);
112
113
		if(count($header) === 2){
114
			$this->responseHeaders->{trim(strtolower($header[0]))} = trim($header[1]);
115
		}
116
		elseif(substr($header_line, 0, 4) === 'HTTP'){
117
			$status = explode(' ', $header_line, 3);
118
119
			$this->responseHeaders->httpversion = explode('/', $status[0], 2)[1];
120
			$this->responseHeaders->statuscode  = intval($status[1]);
121
			$this->responseHeaders->statustext  = trim($status[2]);
122
		}
123
124
		return strlen($header_line);
125
	}
126
127
}
128