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

StreamClient::getResponse()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 45
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 45
rs 8.439
c 0
b 0
f 0
cc 5
eloc 31
nc 8
nop 0
1
<?php
2
/**
3
 * Class StreamClient
4
 *
5
 * @filesource   StreamClient.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
class StreamClient extends HTTPClientAbstract{
18
19
	/**
20
	 * StreamClient constructor.
21
	 *
22
	 * @param \chillerlan\Traits\ContainerInterface $options
23
	 *
24
	 * @throws \chillerlan\HTTP\HTTPClientException
25
	 */
26
	public function __construct(ContainerInterface $options){
27
		parent::__construct($options);
28
29 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...
30
			throw new HTTPClientException('invalid CA file');
31
		}
32
	}
33
34
	/** @inheritdoc */
35
	protected function getResponse():HTTPResponseInterface{
36
		$headers = $this->normalizeRequestHeaders($this->requestHeaders);
37
38
		if(in_array($this->requestMethod, ['PATCH', 'POST', 'PUT', 'DELETE']) && is_array($this->requestBody)){
39
			$this->requestBody = http_build_query($this->requestBody, '', '&', PHP_QUERY_RFC1738);
40
41
			$headers['Content-Type']   = 'Content-Type: application/x-www-form-urlencoded';
42
			$headers['Content-length'] = 'Content-length: '.strlen($this->requestBody);
43
		}
44
45
		$headers['Host']       = 'Host: '.$this->parsedURL['host'].(!empty($this->parsedURL['port']) ? ':'.$this->parsedURL['port'] : '');
46
		$headers['Connection'] = 'Connection: close';
47
48
		$url = $this->requestURL.(!empty($this->requestParams) ? '?'.$this->buildQuery($this->requestParams) : '');
49
50
		$context = stream_context_create([
51
			'http' => [
52
				'method'           => $this->requestMethod,
53
				'header'           => $headers,
54
				'content'          => $this->requestBody,
55
				'protocol_version' => '1.1',
56
				'user_agent'       => $this->options->user_agent,
57
				'max_redirects'    => 0,
58
				'timeout'          => 5,
59
			],
60
			'ssl' => [
61
				'cafile'              => $this->options->ca_info,
62
				'verify_peer'         => true,
63
				'verify_depth'        => 3,
64
				'peer_name'           => $this->parsedURL['host'],
65
				'ciphers'             => 'HIGH:!SSLv2:!SSLv3',
66
				'disable_compression' => true,
67
			],
68
		]);
69
70
		$response         = file_get_contents($url, false, $context);
71
		$responseHeaders  = get_headers($url, 1);
72
73
		return new HTTPResponse([
74
			'url'     => $url,
75
			'headers' => $this->parseResponseHeaders($responseHeaders),
76
			'body'    => trim($response),
77
		]);
78
79
	}
80
81
	/**
82
	 * @param array $headers
83
	 *
84
	 * @return \stdClass
85
	 */
86
	protected function parseResponseHeaders(array $headers):\stdClass {
87
		$h = new \stdClass;
88
89
		foreach($headers as $k => $v){
90
91
			if($k === 0 && substr($v, 0, 4) === 'HTTP'){
92
				$status = explode(' ', $v, 3);
93
94
				$h->httpversion = explode('/', $status[0], 2)[1];
95
				$h->statuscode  = intval($status[1]);
96
				$h->statustext  = trim($status[2]);
97
98
				continue;
99
			}
100
101
			$h->{strtolower($k)} = $v;
102
103
		}
104
105
		return $h;
106
	}
107
108
}
109