Completed
Push — master ( a42702...3550d1 )
by smiley
01:38
created

CurlClient::initCurl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.7333
c 0
b 0
f 0
cc 1
nc 1
nop 0
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 View Code Duplication
	public function __construct(ContainerInterface $options){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
35
		parent::__construct($options);
36
37
		if(!isset($this->options->ca_info) || !is_file($this->options->ca_info)){
38
			throw new HTTPClientException('invalid CA file');
39
		}
40
41
	}
42
43
	/**
44
	 * @return void
45
	 */
46
	protected function initCurl(){
47
		$this->http = curl_init();
48
49
		curl_setopt_array($this->http, [
50
			CURLOPT_HEADER         => false,
51
			CURLOPT_RETURNTRANSFER => true,
52
			CURLOPT_PROTOCOLS      => CURLPROTO_HTTP|CURLPROTO_HTTPS,
53
			CURLOPT_CAINFO         => $this->options->ca_info,
54
			CURLOPT_SSL_VERIFYPEER => true,
55
			CURLOPT_SSL_VERIFYHOST => 2,
56
			CURLOPT_TIMEOUT        => 5,
57
			CURLOPT_USERAGENT      => $this->options->user_agent,
58
		]);
59
60
		curl_setopt_array($this->http, $this->options->curl_options);
61
	}
62
63
	/** @inheritdoc */
64
	protected function getResponse():HTTPResponseInterface{
65
		$this->responseHeaders = new \stdClass;
66
67
		$headers = $this->normalizeRequestHeaders($this->requestHeaders);
68
69
		if(in_array($this->requestMethod, ['PATCH', 'POST', 'PUT', 'DELETE'])){
70
71
			$options = in_array($this->requestMethod, ['PATCH', 'PUT', 'DELETE'])
72
				? [CURLOPT_CUSTOMREQUEST => $this->requestMethod]
73
				: [CURLOPT_POST => true];
74
75
76
			if(!isset($headers['Content-type']) && $this->requestMethod === 'POST' && is_array($this->requestBody)){
77
				$headers += ['Content-type: application/x-www-form-urlencoded'];
78
				$this->requestBody = http_build_query($this->requestBody, '', '&', PHP_QUERY_RFC1738);
79
			}
80
81
			$options += [CURLOPT_POSTFIELDS => $this->requestBody];
82
		}
83
		else{
84
			$options = [CURLOPT_CUSTOMREQUEST => $this->requestMethod];
85
		}
86
87
		$headers += [
88
			'Host: '.$this->parsedURL['host'],
89
			'Connection: close',
90
		];
91
92
		parse_str($this->parsedURL['query'] ?? '', $parsedquery);
93
		$params = array_merge($parsedquery, $this->requestParams);
94
95
		$url = $this->requestURL.(!empty($params) ? '?'.$this->buildQuery($params) : '');
96
97
		$options += [
98
			CURLOPT_URL => $url,
99
			CURLOPT_HTTPHEADER => $headers,
100
			CURLOPT_HEADERFUNCTION => [$this, 'headerLine'],
101
		];
102
103
		$this->initCurl();
104
		curl_setopt_array($this->http, $options);
105
106
		$response  = curl_exec($this->http);
107
		$curl_info = curl_getinfo($this->http);
108
109
		return new HTTPResponse([
110
			'url'       => $url,
111
			'curl_info' => $curl_info,
112
			'headers'   => $this->responseHeaders,
113
			'body'      => $response,
114
		]);
115
	}
116
117
	/**
118
	 * @param resource $curl
119
	 * @param string   $header_line
120
	 *
121
	 * @return int
122
	 *
123
	 * @link http://php.net/manual/function.curl-setopt.php CURLOPT_HEADERFUNCTION
124
	 */
125
	protected function headerLine($curl, $header_line){
126
		$header = explode(':', $header_line, 2);
127
128
		if(count($header) === 2){
129
			$this->responseHeaders->{trim(strtolower($header[0]))} = trim($header[1]);
130
		}
131
		elseif(substr($header_line, 0, 4) === 'HTTP'){
132
			$status = explode(' ', $header_line, 3);
133
134
			$this->responseHeaders->httpversion = explode('/', $status[0], 2)[1];
135
			$this->responseHeaders->statuscode  = intval($status[1]);
136
			$this->responseHeaders->statustext  = trim($status[2]);
137
		}
138
139
		return strlen($header_line);
140
	}
141
142
}
143