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

Native::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 4
rs 10
ccs 3
cts 3
cp 1
cc 1
eloc 2
nc 1
nop 0
crap 1
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
}