Completed
Push — master ( d2fe3d...06bbbd )
by Josh
17:18
created

Native::get()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 2
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
	* @return void
23
	*/
24 5
	public function __construct()
25
	{
26 5
		$this->gzipEnabled = extension_loaded('zlib');
27 5
	}
28
29
	/**
30
	* {@inheritdoc}
31
	*/
32 3
	public function get($url, $headers = [])
33
	{
34 3
		return $this->request('GET', $url, $headers);
35
	}
36
37
	/**
38
	* {@inheritdoc}
39
	*/
40 2
	public function post($url, $headers = [], $body = null)
41
	{
42 2
		return $this->request('POST', $url, $headers, $body);
43
	}
44
45
	/**
46
	* Decompress given page if applicable
47
	*
48
	* @param  string|bool $content Request's response body or FALSE
49
	* @return string|bool
50
	*/
51 5
	protected function decompress($content)
52
	{
53 5
		if ($this->gzipEnabled && substr($content, 0, 2) === "\x1f\x8b")
54 5
		{
55 4
			return gzdecode($content);
56
		}
57
58 1
		return $content;
59
	}
60
61
	/**
62
	* Execute an HTTP request
63
	*
64
	* @param  string      $method  Request method
65
	* @param  string      $url     Request URL
66
	* @param  string[]    $headers Request headers
67
	* @return string|bool          Response body or FALSE
68
	*/
69 5
	protected function request($method, $url, $headers, $body = null)
70
	{
71 5
		$contextOptions = ['http' => ['method' => $method]];
72 5
		if ($this->gzipEnabled)
73 5
		{
74 5
			$headers[] = 'Accept-Encoding: gzip';
75 5
		}
76 5
		if (isset($body))
77 5
		{
78 2
			$headers[] = 'Content-Length: ' . strlen($body);
79 2
			$contextOptions['http']['content'] = $body;
80 2
		}
81 5
		if (!empty($headers))
82 5
		{
83 5
			$contextOptions['http']['header'] = $headers;
84 5
		}
85
86 5
		return $this->decompress(@file_get_contents($url, false, stream_context_create($contextOptions)));
87
	}
88
}