Completed
Push — master ( 0c606d...0489bb )
by Josh
18:01
created

Native   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 77
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 4
Bugs 0 Features 2
Metric Value
wmc 9
c 4
b 0
f 2
lcom 1
cbo 1
dl 0
loc 77
ccs 28
cts 28
cp 1
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A get() 0 4 1
A post() 0 4 1
A decompress() 0 9 3
A request() 0 21 3
1
<?php
2
3
/**
4
* @package   s9e\TextFormatter
5
* @copyright Copyright (c) 2010-2016 The s9e Authors
6
* @license   http://www.opensource.org/licenses/mit-license.php The MIT License
7
*/
8
namespace s9e\TextFormatter\Configurator\Helpers\Http\Clients;
9
10
use s9e\TextFormatter\Configurator\Helpers\Http\Client;
11
12
class Native extends Client
13
{
14
	/**
15
	* @var bool Whether to use gzip encoding
16
	*/
17
	public $gzipEnabled;
18
19
	/**
20
	* Constructor
21
	*/
22 6
	public function __construct()
23
	{
24 6
		$this->gzipEnabled = extension_loaded('zlib');
25 6
	}
26
27
	/**
28
	* {@inheritdoc}
29
	*/
30 3
	public function get($url, $headers = [])
31
	{
32 3
		return $this->request('GET', $url, $headers);
33
	}
34
35
	/**
36
	* {@inheritdoc}
37
	*/
38 3
	public function post($url, $headers = [], $body = '')
39
	{
40 3
		return $this->request('POST', $url, $headers, $body);
41
	}
42
43
	/**
44
	* Decompress given page if applicable
45
	*
46
	* @param  string|bool $content Request's response body or FALSE
47
	* @return string|bool
48
	*/
49 6
	protected function decompress($content)
50
	{
51 6
		if ($this->gzipEnabled && substr($content, 0, 2) === "\x1f\x8b")
52 6
		{
53 5
			return gzdecode($content);
54
		}
55
56 1
		return $content;
57
	}
58
59
	/**
60
	* Execute an HTTP request
61
	*
62
	* @param  string      $method  Request method
63
	* @param  string      $url     Request URL
64
	* @param  string[]    $headers Request headers
65
	* @return string|bool          Response body or FALSE
66
	*/
67 6
	protected function request($method, $url, $headers, $body = null)
68
	{
69
		$contextOptions = [
70
			'http' => [
71 6
				'method'  => $method,
72 6
				'timeout' => $this->timeout
73 6
			]
74 6
		];
75 6
		if ($this->gzipEnabled)
76 6
		{
77 6
			$headers[] = 'Accept-Encoding: gzip';
78 6
		}
79 6
		if (isset($body))
80 6
		{
81 3
			$headers[] = 'Content-Length: ' . strlen($body);
82 3
			$contextOptions['http']['content'] = $body;
83 3
		}
84 6
		$contextOptions['http']['header'] = $headers;
85
86 6
		return $this->decompress(@file_get_contents($url, false, stream_context_create($contextOptions)));
87
	}
88
}